babylon.max.js 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. /**
  1369. * Ray from a pointer if availible (eg. 6dof controller)
  1370. */
  1371. _this.ray = null;
  1372. _this.skipOnPointerObservable = false;
  1373. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1374. return _this;
  1375. }
  1376. return PointerInfoPre;
  1377. }(PointerInfoBase));
  1378. BABYLON.PointerInfoPre = PointerInfoPre;
  1379. /**
  1380. * This type contains all the data related to a pointer event in Babylon.js.
  1381. * 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.
  1382. */
  1383. var PointerInfo = /** @class */ (function (_super) {
  1384. __extends(PointerInfo, _super);
  1385. function PointerInfo(type, event, pickInfo) {
  1386. var _this = _super.call(this, type, event) || this;
  1387. _this.pickInfo = pickInfo;
  1388. return _this;
  1389. }
  1390. return PointerInfo;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfo = PointerInfo;
  1393. })(BABYLON || (BABYLON = {}));
  1394. //# sourceMappingURL=babylon.pointerEvents.js.map
  1395. var BABYLON;
  1396. (function (BABYLON) {
  1397. BABYLON.ToGammaSpace = 1 / 2.2;
  1398. BABYLON.ToLinearSpace = 2.2;
  1399. BABYLON.Epsilon = 0.001;
  1400. /**
  1401. * Class used to hold a RBG color
  1402. */
  1403. var Color3 = /** @class */ (function () {
  1404. /**
  1405. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1406. * @param r defines the red component (between 0 and 1, default is 0)
  1407. * @param g defines the green component (between 0 and 1, default is 0)
  1408. * @param b defines the blue component (between 0 and 1, default is 0)
  1409. */
  1410. function Color3(
  1411. /**
  1412. * Defines the red component (between 0 and 1, default is 0)
  1413. */
  1414. r,
  1415. /**
  1416. * Defines the green component (between 0 and 1, default is 0)
  1417. */
  1418. g,
  1419. /**
  1420. * Defines the blue component (between 0 and 1, default is 0)
  1421. */
  1422. b) {
  1423. if (r === void 0) { r = 0; }
  1424. if (g === void 0) { g = 0; }
  1425. if (b === void 0) { b = 0; }
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. }
  1430. /**
  1431. * Creates a string with the Color3 current values
  1432. * @returns the string representation of the Color3 object
  1433. */
  1434. Color3.prototype.toString = function () {
  1435. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1436. };
  1437. /**
  1438. * Returns the string "Color3"
  1439. * @returns "Color3"
  1440. */
  1441. Color3.prototype.getClassName = function () {
  1442. return "Color3";
  1443. };
  1444. /**
  1445. * Compute the Color3 hash code
  1446. * @returns an unique number that can be used to hash Color3 objects
  1447. */
  1448. Color3.prototype.getHashCode = function () {
  1449. var hash = this.r || 0;
  1450. hash = (hash * 397) ^ (this.g || 0);
  1451. hash = (hash * 397) ^ (this.b || 0);
  1452. return hash;
  1453. };
  1454. // Operators
  1455. /**
  1456. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1457. * @param array defines the array where to store the r,g,b components
  1458. * @param index defines an optional index in the target array to define where to start storing values
  1459. * @returns the current Color3 object
  1460. */
  1461. Color3.prototype.toArray = function (array, index) {
  1462. if (index === undefined) {
  1463. index = 0;
  1464. }
  1465. array[index] = this.r;
  1466. array[index + 1] = this.g;
  1467. array[index + 2] = this.b;
  1468. return this;
  1469. };
  1470. /**
  1471. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1472. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1473. * @returns a new {BABYLON.Color4} object
  1474. */
  1475. Color3.prototype.toColor4 = function (alpha) {
  1476. if (alpha === void 0) { alpha = 1; }
  1477. return new Color4(this.r, this.g, this.b, alpha);
  1478. };
  1479. /**
  1480. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1481. * @returns the new array
  1482. */
  1483. Color3.prototype.asArray = function () {
  1484. var result = new Array();
  1485. this.toArray(result, 0);
  1486. return result;
  1487. };
  1488. /**
  1489. * Returns the luminance value
  1490. * @returns a float value
  1491. */
  1492. Color3.prototype.toLuminance = function () {
  1493. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1494. };
  1495. /**
  1496. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1497. * @param otherColor defines the second operand
  1498. * @returns the new Color3 object
  1499. */
  1500. Color3.prototype.multiply = function (otherColor) {
  1501. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1502. };
  1503. /**
  1504. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1505. * @param otherColor defines the second operand
  1506. * @param result defines the Color3 object where to store the result
  1507. * @returns the current Color3
  1508. */
  1509. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1510. result.r = this.r * otherColor.r;
  1511. result.g = this.g * otherColor.g;
  1512. result.b = this.b * otherColor.b;
  1513. return this;
  1514. };
  1515. /**
  1516. * Determines equality between Color3 objects
  1517. * @param otherColor defines the second operand
  1518. * @returns true if the rgb values are equal to the given ones
  1519. */
  1520. Color3.prototype.equals = function (otherColor) {
  1521. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1522. };
  1523. /**
  1524. * Determines equality between the current Color3 object and a set of r,b,g values
  1525. * @param r defines the red component to check
  1526. * @param g defines the green component to check
  1527. * @param b defines the blue component to check
  1528. * @returns true if the rgb values are equal to the given ones
  1529. */
  1530. Color3.prototype.equalsFloats = function (r, g, b) {
  1531. return this.r === r && this.g === g && this.b === b;
  1532. };
  1533. /**
  1534. * Multiplies in place each rgb value by scale
  1535. * @param scale defines the scaling factor
  1536. * @returns the updated Color3
  1537. */
  1538. Color3.prototype.scale = function (scale) {
  1539. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1540. };
  1541. /**
  1542. * Multiplies the rgb values by scale and stores the result into "result"
  1543. * @param scale defines the scaling factor
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the unmodified current Color3
  1546. */
  1547. Color3.prototype.scaleToRef = function (scale, result) {
  1548. result.r = this.r * scale;
  1549. result.g = this.g * scale;
  1550. result.b = this.b * scale;
  1551. return this;
  1552. };
  1553. /**
  1554. * Scale the current Color3 values by a factor and add the result to a given Color3
  1555. * @param scale defines the scale factor
  1556. * @param result defines color to store the result into
  1557. * @returns the unmodified current Color3
  1558. */
  1559. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1560. result.r += this.r * scale;
  1561. result.g += this.g * scale;
  1562. result.b += this.b * scale;
  1563. return this;
  1564. };
  1565. /**
  1566. * Clamps the rgb values by the min and max values and stores the result into "result"
  1567. * @param min defines minimum clamping value (default is 0)
  1568. * @param max defines maximum clamping value (default is 1)
  1569. * @param result defines color to store the result into
  1570. * @returns the original Color3
  1571. */
  1572. Color3.prototype.clampToRef = function (min, max, result) {
  1573. if (min === void 0) { min = 0; }
  1574. if (max === void 0) { max = 1; }
  1575. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1576. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1577. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1578. return this;
  1579. };
  1580. /**
  1581. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1582. * @param otherColor defines the second operand
  1583. * @returns the new Color3
  1584. */
  1585. Color3.prototype.add = function (otherColor) {
  1586. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1587. };
  1588. /**
  1589. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1590. * @param otherColor defines the second operand
  1591. * @param result defines Color3 object to store the result into
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.addToRef = function (otherColor, result) {
  1595. result.r = this.r + otherColor.r;
  1596. result.g = this.g + otherColor.g;
  1597. result.b = this.b + otherColor.b;
  1598. return this;
  1599. };
  1600. /**
  1601. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1602. * @param otherColor defines the second operand
  1603. * @returns the new Color3
  1604. */
  1605. Color3.prototype.subtract = function (otherColor) {
  1606. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1607. };
  1608. /**
  1609. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1610. * @param otherColor defines the second operand
  1611. * @param result defines Color3 object to store the result into
  1612. * @returns the unmodified current Color3
  1613. */
  1614. Color3.prototype.subtractToRef = function (otherColor, result) {
  1615. result.r = this.r - otherColor.r;
  1616. result.g = this.g - otherColor.g;
  1617. result.b = this.b - otherColor.b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Copy the current object
  1622. * @returns a new Color3 copied the current one
  1623. */
  1624. Color3.prototype.clone = function () {
  1625. return new Color3(this.r, this.g, this.b);
  1626. };
  1627. /**
  1628. * Copies the rgb values from the source in the current Color3
  1629. * @param source defines the source Color3 object
  1630. * @returns the updated Color3 object
  1631. */
  1632. Color3.prototype.copyFrom = function (source) {
  1633. this.r = source.r;
  1634. this.g = source.g;
  1635. this.b = source.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.copyFromFloats = function (r, g, b) {
  1646. this.r = r;
  1647. this.g = g;
  1648. this.b = b;
  1649. return this;
  1650. };
  1651. /**
  1652. * Updates the Color3 rgb values from the given floats
  1653. * @param r defines the red component to read from
  1654. * @param g defines the green component to read from
  1655. * @param b defines the blue component to read from
  1656. * @returns the current Color3 object
  1657. */
  1658. Color3.prototype.set = function (r, g, b) {
  1659. return this.copyFromFloats(r, g, b);
  1660. };
  1661. /**
  1662. * Compute the Color3 hexadecimal code as a string
  1663. * @returns a string containing the hexadecimal representation of the Color3 object
  1664. */
  1665. Color3.prototype.toHexString = function () {
  1666. var intR = (this.r * 255) | 0;
  1667. var intG = (this.g * 255) | 0;
  1668. var intB = (this.b * 255) | 0;
  1669. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1670. };
  1671. /**
  1672. * Computes a new Color3 converted from the current one to linear space
  1673. * @returns a new Color3 object
  1674. */
  1675. Color3.prototype.toLinearSpace = function () {
  1676. var convertedColor = new Color3();
  1677. this.toLinearSpaceToRef(convertedColor);
  1678. return convertedColor;
  1679. };
  1680. /**
  1681. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1682. * @param convertedColor defines the Color3 object where to store the linear space version
  1683. * @returns the unmodified Color3
  1684. */
  1685. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1686. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1687. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1688. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1689. return this;
  1690. };
  1691. /**
  1692. * Computes a new Color3 converted from the current one to gamma space
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.prototype.toGammaSpace = function () {
  1696. var convertedColor = new Color3();
  1697. this.toGammaSpaceToRef(convertedColor);
  1698. return convertedColor;
  1699. };
  1700. /**
  1701. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1702. * @param convertedColor defines the Color3 object where to store the gamma space version
  1703. * @returns the unmodified Color3
  1704. */
  1705. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1706. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1707. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1708. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1709. return this;
  1710. };
  1711. // Statics
  1712. /**
  1713. * Creates a new Color3 from the string containing valid hexadecimal values
  1714. * @param hex defines a string containing valid hexadecimal values
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.FromHexString = function (hex) {
  1718. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1719. return new Color3(0, 0, 0);
  1720. }
  1721. var r = parseInt(hex.substring(1, 3), 16);
  1722. var g = parseInt(hex.substring(3, 5), 16);
  1723. var b = parseInt(hex.substring(5, 7), 16);
  1724. return Color3.FromInts(r, g, b);
  1725. };
  1726. /**
  1727. * Creates a new Vector3 from the starting index of the given array
  1728. * @param array defines the source array
  1729. * @param offset defines an offset in the source array
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromArray = function (array, offset) {
  1733. if (offset === void 0) { offset = 0; }
  1734. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1735. };
  1736. /**
  1737. * Creates a new Color3 from integer values (< 256)
  1738. * @param r defines the red component to read from (value between 0 and 255)
  1739. * @param g defines the green component to read from (value between 0 and 255)
  1740. * @param b defines the blue component to read from (value between 0 and 255)
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromInts = function (r, g, b) {
  1744. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1745. };
  1746. /**
  1747. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1748. * @param start defines the start Color3 value
  1749. * @param end defines the end Color3 value
  1750. * @param amount defines the gradient value between start and end
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.Lerp = function (start, end, amount) {
  1754. var r = start.r + ((end.r - start.r) * amount);
  1755. var g = start.g + ((end.g - start.g) * amount);
  1756. var b = start.b + ((end.b - start.b) * amount);
  1757. return new Color3(r, g, b);
  1758. };
  1759. /**
  1760. * Returns a Color3 value containing a red color
  1761. * @returns a new Color3 object
  1762. */
  1763. Color3.Red = function () { return new Color3(1, 0, 0); };
  1764. /**
  1765. * Returns a Color3 value containing a green color
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Green = function () { return new Color3(0, 1, 0); };
  1769. /**
  1770. * Returns a Color3 value containing a blue color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1774. /**
  1775. * Returns a Color3 value containing a black color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Black = function () { return new Color3(0, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a white color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.White = function () { return new Color3(1, 1, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a purple color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1789. /**
  1790. * Returns a Color3 value containing a magenta color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a yellow color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1799. /**
  1800. * Returns a Color3 value containing a gray color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a teal color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1809. /**
  1810. * Returns a Color3 value containing a random color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1814. return Color3;
  1815. }());
  1816. BABYLON.Color3 = Color3;
  1817. /**
  1818. * Class used to hold a RBGA color
  1819. */
  1820. var Color4 = /** @class */ (function () {
  1821. /**
  1822. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1823. * @param r defines the red component (between 0 and 1, default is 0)
  1824. * @param g defines the green component (between 0 and 1, default is 0)
  1825. * @param b defines the blue component (between 0 and 1, default is 0)
  1826. * @param a defines the alpha component (between 0 and 1, default is 1)
  1827. */
  1828. function Color4(
  1829. /**
  1830. * Defines the red component (between 0 and 1, default is 0)
  1831. */
  1832. r,
  1833. /**
  1834. * Defines the green component (between 0 and 1, default is 0)
  1835. */
  1836. g,
  1837. /**
  1838. * Defines the blue component (between 0 and 1, default is 0)
  1839. */
  1840. b,
  1841. /**
  1842. * Defines the alpha component (between 0 and 1, default is 1)
  1843. */
  1844. a) {
  1845. if (r === void 0) { r = 0; }
  1846. if (g === void 0) { g = 0; }
  1847. if (b === void 0) { b = 0; }
  1848. if (a === void 0) { a = 1; }
  1849. this.r = r;
  1850. this.g = g;
  1851. this.b = b;
  1852. this.a = a;
  1853. }
  1854. // Operators
  1855. /**
  1856. * Adds in place the given Color4 values to the current Color4 object
  1857. * @param right defines the second operand
  1858. * @returns the current updated Color4 object
  1859. */
  1860. Color4.prototype.addInPlace = function (right) {
  1861. this.r += right.r;
  1862. this.g += right.g;
  1863. this.b += right.b;
  1864. this.a += right.a;
  1865. return this;
  1866. };
  1867. /**
  1868. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1869. * @returns the new array
  1870. */
  1871. Color4.prototype.asArray = function () {
  1872. var result = new Array();
  1873. this.toArray(result, 0);
  1874. return result;
  1875. };
  1876. /**
  1877. * Stores from the starting index in the given array the Color4 successive values
  1878. * @param array defines the array where to store the r,g,b components
  1879. * @param index defines an optional index in the target array to define where to start storing values
  1880. * @returns the current Color4 object
  1881. */
  1882. Color4.prototype.toArray = function (array, index) {
  1883. if (index === undefined) {
  1884. index = 0;
  1885. }
  1886. array[index] = this.r;
  1887. array[index + 1] = this.g;
  1888. array[index + 2] = this.b;
  1889. array[index + 3] = this.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1894. * @param right defines the second operand
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.add = function (right) {
  1898. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1899. };
  1900. /**
  1901. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1902. * @param right defines the second operand
  1903. * @returns a new Color4 object
  1904. */
  1905. Color4.prototype.subtract = function (right) {
  1906. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1907. };
  1908. /**
  1909. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1910. * @param right defines the second operand
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the current Color4 object
  1913. */
  1914. Color4.prototype.subtractToRef = function (right, result) {
  1915. result.r = this.r - right.r;
  1916. result.g = this.g - right.g;
  1917. result.b = this.b - right.b;
  1918. result.a = this.a - right.a;
  1919. return this;
  1920. };
  1921. /**
  1922. * Creates a new Color4 with the current Color4 values multiplied by scale
  1923. * @param scale defines the scaling factor to apply
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.scale = function (scale) {
  1927. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1928. };
  1929. /**
  1930. * Multiplies the current Color4 values by scale and stores the result in "result"
  1931. * @param scale defines the scaling factor to apply
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current unmodified Color4
  1934. */
  1935. Color4.prototype.scaleToRef = function (scale, result) {
  1936. result.r = this.r * scale;
  1937. result.g = this.g * scale;
  1938. result.b = this.b * scale;
  1939. result.a = this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Scale the current Color4 values by a factor and add the result to a given Color4
  1944. * @param scale defines the scale factor
  1945. * @param result defines the Color4 object where to store the result
  1946. * @returns the unmodified current Color4
  1947. */
  1948. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1949. result.r += this.r * scale;
  1950. result.g += this.g * scale;
  1951. result.b += this.b * scale;
  1952. result.a += this.a * scale;
  1953. return this;
  1954. };
  1955. /**
  1956. * Clamps the rgb values by the min and max values and stores the result into "result"
  1957. * @param min defines minimum clamping value (default is 0)
  1958. * @param max defines maximum clamping value (default is 1)
  1959. * @param result defines color to store the result into.
  1960. * @returns the cuurent Color4
  1961. */
  1962. Color4.prototype.clampToRef = function (min, max, result) {
  1963. if (min === void 0) { min = 0; }
  1964. if (max === void 0) { max = 1; }
  1965. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1966. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1967. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1968. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1969. return this;
  1970. };
  1971. /**
  1972. * Multipy an Color4 value by another and return a new Color4 object
  1973. * @param color defines the Color4 value to multiply by
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.multiply = function (color) {
  1977. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1978. };
  1979. /**
  1980. * Multipy a Color4 value by another and push the result in a reference value
  1981. * @param color defines the Color4 value to multiply by
  1982. * @param result defines the Color4 to fill the result in
  1983. * @returns the result Color4
  1984. */
  1985. Color4.prototype.multiplyToRef = function (color, result) {
  1986. result.r = this.r * color.r;
  1987. result.g = this.g * color.g;
  1988. result.b = this.b * color.b;
  1989. result.a = this.a * color.a;
  1990. return result;
  1991. };
  1992. /**
  1993. * Creates a string with the Color4 current values
  1994. * @returns the string representation of the Color4 object
  1995. */
  1996. Color4.prototype.toString = function () {
  1997. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1998. };
  1999. /**
  2000. * Returns the string "Color4"
  2001. * @returns "Color4"
  2002. */
  2003. Color4.prototype.getClassName = function () {
  2004. return "Color4";
  2005. };
  2006. /**
  2007. * Compute the Color4 hash code
  2008. * @returns an unique number that can be used to hash Color4 objects
  2009. */
  2010. Color4.prototype.getHashCode = function () {
  2011. var hash = this.r || 0;
  2012. hash = (hash * 397) ^ (this.g || 0);
  2013. hash = (hash * 397) ^ (this.b || 0);
  2014. hash = (hash * 397) ^ (this.a || 0);
  2015. return hash;
  2016. };
  2017. /**
  2018. * Creates a new Color4 copied from the current one
  2019. * @returns a new Color4 object
  2020. */
  2021. Color4.prototype.clone = function () {
  2022. return new Color4(this.r, this.g, this.b, this.a);
  2023. };
  2024. /**
  2025. * Copies the given Color4 values into the current one
  2026. * @param source defines the source Color4 object
  2027. * @returns the current updated Color4 object
  2028. */
  2029. Color4.prototype.copyFrom = function (source) {
  2030. this.r = source.r;
  2031. this.g = source.g;
  2032. this.b = source.b;
  2033. this.a = source.a;
  2034. return this;
  2035. };
  2036. /**
  2037. * Copies the given float values into the current one
  2038. * @param r defines the red component to read from
  2039. * @param g defines the green component to read from
  2040. * @param b defines the blue component to read from
  2041. * @param a defines the alpha component to read from
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2045. this.r = r;
  2046. this.g = g;
  2047. this.b = b;
  2048. this.a = a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the given float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.set = function (r, g, b, a) {
  2060. return this.copyFromFloats(r, g, b, a);
  2061. };
  2062. /**
  2063. * Compute the Color4 hexadecimal code as a string
  2064. * @returns a string containing the hexadecimal representation of the Color4 object
  2065. */
  2066. Color4.prototype.toHexString = function () {
  2067. var intR = (this.r * 255) | 0;
  2068. var intG = (this.g * 255) | 0;
  2069. var intB = (this.b * 255) | 0;
  2070. var intA = (this.a * 255) | 0;
  2071. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2072. };
  2073. /**
  2074. * Computes a new Color4 converted from the current one to linear space
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.prototype.toLinearSpace = function () {
  2078. var convertedColor = new Color4();
  2079. this.toLinearSpaceToRef(convertedColor);
  2080. return convertedColor;
  2081. };
  2082. /**
  2083. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2084. * @param convertedColor defines the Color4 object where to store the linear space version
  2085. * @returns the unmodified Color4
  2086. */
  2087. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2088. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2089. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2090. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2091. convertedColor.a = this.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Computes a new Color4 converted from the current one to gamma space
  2096. * @returns a new Color4 object
  2097. */
  2098. Color4.prototype.toGammaSpace = function () {
  2099. var convertedColor = new Color4();
  2100. this.toGammaSpaceToRef(convertedColor);
  2101. return convertedColor;
  2102. };
  2103. /**
  2104. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2105. * @param convertedColor defines the Color4 object where to store the gamma space version
  2106. * @returns the unmodified Color4
  2107. */
  2108. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2109. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2110. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2111. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2112. convertedColor.a = this.a;
  2113. return this;
  2114. };
  2115. // Statics
  2116. /**
  2117. * Creates a new Color4 from the string containing valid hexadecimal values
  2118. * @param hex defines a string containing valid hexadecimal values
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.FromHexString = function (hex) {
  2122. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2123. return new Color4(0.0, 0.0, 0.0, 0.0);
  2124. }
  2125. var r = parseInt(hex.substring(1, 3), 16);
  2126. var g = parseInt(hex.substring(3, 5), 16);
  2127. var b = parseInt(hex.substring(5, 7), 16);
  2128. var a = parseInt(hex.substring(7, 9), 16);
  2129. return Color4.FromInts(r, g, b, a);
  2130. };
  2131. /**
  2132. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2133. * @param left defines the start value
  2134. * @param right defines the end value
  2135. * @param amount defines the gradient factor
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.Lerp = function (left, right, amount) {
  2139. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2140. Color4.LerpToRef(left, right, amount, result);
  2141. return result;
  2142. };
  2143. /**
  2144. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2145. * @param left defines the start value
  2146. * @param right defines the end value
  2147. * @param amount defines the gradient factor
  2148. * @param result defines the Color4 object where to store data
  2149. */
  2150. Color4.LerpToRef = function (left, right, amount, result) {
  2151. result.r = left.r + (right.r - left.r) * amount;
  2152. result.g = left.g + (right.g - left.g) * amount;
  2153. result.b = left.b + (right.b - left.b) * amount;
  2154. result.a = left.a + (right.a - left.a) * amount;
  2155. };
  2156. /**
  2157. * Creates a new Color4 from the starting index element of the given array
  2158. * @param array defines the source array to read from
  2159. * @param offset defines the offset in the source array
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.FromArray = function (array, offset) {
  2163. if (offset === void 0) { offset = 0; }
  2164. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2165. };
  2166. /**
  2167. * Creates a new Color3 from integer values (< 256)
  2168. * @param r defines the red component to read from (value between 0 and 255)
  2169. * @param g defines the green component to read from (value between 0 and 255)
  2170. * @param b defines the blue component to read from (value between 0 and 255)
  2171. * @param a defines the alpha component to read from (value between 0 and 255)
  2172. * @returns a new Color3 object
  2173. */
  2174. Color4.FromInts = function (r, g, b, a) {
  2175. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2176. };
  2177. /**
  2178. * Check the content of a given array and convert it to an array containing RGBA data
  2179. * If the original array was already containing count * 4 values then it is returned directly
  2180. * @param colors defines the array to check
  2181. * @param count defines the number of RGBA data to expect
  2182. * @returns an array containing count * 4 values (RGBA)
  2183. */
  2184. Color4.CheckColors4 = function (colors, count) {
  2185. // Check if color3 was used
  2186. if (colors.length === count * 3) {
  2187. var colors4 = [];
  2188. for (var index = 0; index < colors.length; index += 3) {
  2189. var newIndex = (index / 3) * 4;
  2190. colors4[newIndex] = colors[index];
  2191. colors4[newIndex + 1] = colors[index + 1];
  2192. colors4[newIndex + 2] = colors[index + 2];
  2193. colors4[newIndex + 3] = 1.0;
  2194. }
  2195. return colors4;
  2196. }
  2197. return colors;
  2198. };
  2199. return Color4;
  2200. }());
  2201. BABYLON.Color4 = Color4;
  2202. /**
  2203. * Class representing a vector containing 2 coordinates
  2204. */
  2205. var Vector2 = /** @class */ (function () {
  2206. /**
  2207. * Creates a new Vector2 from the given x and y coordinates
  2208. * @param x defines the first coordinate
  2209. * @param y defines the second coordinate
  2210. */
  2211. function Vector2(
  2212. /** defines the first coordinate */
  2213. x,
  2214. /** defines the second coordinate */
  2215. y) {
  2216. this.x = x;
  2217. this.y = y;
  2218. }
  2219. /**
  2220. * Gets a string with the Vector2 coordinates
  2221. * @returns a string with the Vector2 coordinates
  2222. */
  2223. Vector2.prototype.toString = function () {
  2224. return "{X: " + this.x + " Y:" + this.y + "}";
  2225. };
  2226. /**
  2227. * Gets class name
  2228. * @returns the string "Vector2"
  2229. */
  2230. Vector2.prototype.getClassName = function () {
  2231. return "Vector2";
  2232. };
  2233. /**
  2234. * Gets current vector hash code
  2235. * @returns the Vector2 hash code as a number
  2236. */
  2237. Vector2.prototype.getHashCode = function () {
  2238. var hash = this.x || 0;
  2239. hash = (hash * 397) ^ (this.y || 0);
  2240. return hash;
  2241. };
  2242. // Operators
  2243. /**
  2244. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2245. * @param array defines the source array
  2246. * @param index defines the offset in source array
  2247. * @returns the current Vector2
  2248. */
  2249. Vector2.prototype.toArray = function (array, index) {
  2250. if (index === void 0) { index = 0; }
  2251. array[index] = this.x;
  2252. array[index + 1] = this.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Copy the current vector to an array
  2257. * @returns a new array with 2 elements: the Vector2 coordinates.
  2258. */
  2259. Vector2.prototype.asArray = function () {
  2260. var result = new Array();
  2261. this.toArray(result, 0);
  2262. return result;
  2263. };
  2264. /**
  2265. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2266. * @param source defines the source Vector2
  2267. * @returns the current updated Vector2
  2268. */
  2269. Vector2.prototype.copyFrom = function (source) {
  2270. this.x = source.x;
  2271. this.y = source.y;
  2272. return this;
  2273. };
  2274. /**
  2275. * Sets the Vector2 coordinates with the given floats
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. * @returns the current updated Vector2
  2279. */
  2280. Vector2.prototype.copyFromFloats = function (x, y) {
  2281. this.x = x;
  2282. this.y = y;
  2283. return this;
  2284. };
  2285. /**
  2286. * Sets the Vector2 coordinates with the given floats
  2287. * @param x defines the first coordinate
  2288. * @param y defines the second coordinate
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.set = function (x, y) {
  2292. return this.copyFromFloats(x, y);
  2293. };
  2294. /**
  2295. * Add another vector with the current one
  2296. * @param otherVector defines the other vector
  2297. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2298. */
  2299. Vector2.prototype.add = function (otherVector) {
  2300. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2301. };
  2302. /**
  2303. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2304. * @param otherVector defines the other vector
  2305. * @param result defines the target vector
  2306. * @returns the unmodified current Vector2
  2307. */
  2308. Vector2.prototype.addToRef = function (otherVector, result) {
  2309. result.x = this.x + otherVector.x;
  2310. result.y = this.y + otherVector.y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2315. * @param otherVector defines the other vector
  2316. * @returns the current updated Vector2
  2317. */
  2318. Vector2.prototype.addInPlace = function (otherVector) {
  2319. this.x += otherVector.x;
  2320. this.y += otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns a new Vector2
  2327. */
  2328. Vector2.prototype.addVector3 = function (otherVector) {
  2329. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2330. };
  2331. /**
  2332. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2333. * @param otherVector defines the other vector
  2334. * @returns a new Vector2
  2335. */
  2336. Vector2.prototype.subtract = function (otherVector) {
  2337. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2338. };
  2339. /**
  2340. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2341. * @param otherVector defines the other vector
  2342. * @param result defines the target vector
  2343. * @returns the unmodified current Vector2
  2344. */
  2345. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2346. result.x = this.x - otherVector.x;
  2347. result.y = this.y - otherVector.y;
  2348. return this;
  2349. };
  2350. /**
  2351. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2352. * @param otherVector defines the other vector
  2353. * @returns the current updated Vector2
  2354. */
  2355. Vector2.prototype.subtractInPlace = function (otherVector) {
  2356. this.x -= otherVector.x;
  2357. this.y -= otherVector.y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Multiplies in place the current Vector2 coordinates by the given ones
  2362. * @param otherVector defines the other vector
  2363. * @returns the current updated Vector2
  2364. */
  2365. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2366. this.x *= otherVector.x;
  2367. this.y *= otherVector.y;
  2368. return this;
  2369. };
  2370. /**
  2371. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2372. * @param otherVector defines the other vector
  2373. * @returns a new Vector2
  2374. */
  2375. Vector2.prototype.multiply = function (otherVector) {
  2376. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2377. };
  2378. /**
  2379. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @param result defines the target vector
  2382. * @returns the unmodified current Vector2
  2383. */
  2384. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2385. result.x = this.x * otherVector.x;
  2386. result.y = this.y * otherVector.y;
  2387. return this;
  2388. };
  2389. /**
  2390. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2391. * @param x defines the first coordinate
  2392. * @param y defines the second coordinate
  2393. * @returns a new Vector2
  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 given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.divide = function (otherVector) {
  2404. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2405. };
  2406. /**
  2407. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.divideToRef = function (otherVector, result) {
  2413. result.x = this.x / otherVector.x;
  2414. result.y = this.y / otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Divides the current Vector3 coordinates by the given ones
  2419. * @param otherVector defines the other vector
  2420. * @returns the current updated Vector2
  2421. */
  2422. Vector2.prototype.divideInPlace = function (otherVector) {
  2423. return this.divideToRef(otherVector, this);
  2424. };
  2425. /**
  2426. * Gets a new Vector2 with current Vector2 negated coordinates
  2427. * @returns a new Vector2
  2428. */
  2429. Vector2.prototype.negate = function () {
  2430. return new Vector2(-this.x, -this.y);
  2431. };
  2432. /**
  2433. * Multiply the Vector2 coordinates by scale
  2434. * @param scale defines the scaling factor
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.scaleInPlace = function (scale) {
  2438. this.x *= scale;
  2439. this.y *= scale;
  2440. return this;
  2441. };
  2442. /**
  2443. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2444. * @param scale defines the scaling factor
  2445. * @returns a new Vector2
  2446. */
  2447. Vector2.prototype.scale = function (scale) {
  2448. var result = new Vector2(0, 0);
  2449. this.scaleToRef(scale, result);
  2450. return result;
  2451. };
  2452. /**
  2453. * Scale the current Vector2 values by a factor to a given Vector2
  2454. * @param scale defines the scale factor
  2455. * @param result defines the Vector2 object where to store the result
  2456. * @returns the unmodified current Vector2
  2457. */
  2458. Vector2.prototype.scaleToRef = function (scale, result) {
  2459. result.x = this.x * scale;
  2460. result.y = this.y * scale;
  2461. return this;
  2462. };
  2463. /**
  2464. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2465. * @param scale defines the scale factor
  2466. * @param result defines the Vector2 object where to store the result
  2467. * @returns the unmodified current Vector2
  2468. */
  2469. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2470. result.x += this.x * scale;
  2471. result.y += this.y * scale;
  2472. return this;
  2473. };
  2474. /**
  2475. * Gets a boolean if two vectors are equals
  2476. * @param otherVector defines the other vector
  2477. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2478. */
  2479. Vector2.prototype.equals = function (otherVector) {
  2480. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2481. };
  2482. /**
  2483. * Gets a boolean if two vectors are equals (using an epsilon value)
  2484. * @param otherVector defines the other vector
  2485. * @param epsilon defines the minimal distance to consider equality
  2486. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2487. */
  2488. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2489. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2490. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2491. };
  2492. // Properties
  2493. /**
  2494. * Gets the length of the vector
  2495. * @returns the vector length (float)
  2496. */
  2497. Vector2.prototype.length = function () {
  2498. return Math.sqrt(this.x * this.x + this.y * this.y);
  2499. };
  2500. /**
  2501. * Gets the vector squared length
  2502. * @returns the vector squared length (float)
  2503. */
  2504. Vector2.prototype.lengthSquared = function () {
  2505. return (this.x * this.x + this.y * this.y);
  2506. };
  2507. // Methods
  2508. /**
  2509. * Normalize the vector
  2510. * @returns the current updated Vector2
  2511. */
  2512. Vector2.prototype.normalize = function () {
  2513. var len = this.length();
  2514. if (len === 0)
  2515. return this;
  2516. var num = 1.0 / len;
  2517. this.x *= num;
  2518. this.y *= num;
  2519. return this;
  2520. };
  2521. /**
  2522. * Gets a new Vector2 copied from the Vector2
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.clone = function () {
  2526. return new Vector2(this.x, this.y);
  2527. };
  2528. // Statics
  2529. /**
  2530. * Gets a new Vector2(0, 0)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.Zero = function () {
  2534. return new Vector2(0, 0);
  2535. };
  2536. /**
  2537. * Gets a new Vector2(1, 1)
  2538. * @returns a new Vector2
  2539. */
  2540. Vector2.One = function () {
  2541. return new Vector2(1, 1);
  2542. };
  2543. /**
  2544. * Gets a new Vector2 set from the given index element of the given array
  2545. * @param array defines the data source
  2546. * @param offset defines the offset in the data source
  2547. * @returns a new Vector2
  2548. */
  2549. Vector2.FromArray = function (array, offset) {
  2550. if (offset === void 0) { offset = 0; }
  2551. return new Vector2(array[offset], array[offset + 1]);
  2552. };
  2553. /**
  2554. * Sets "result" from the given index element of the given array
  2555. * @param array defines the data source
  2556. * @param offset defines the offset in the data source
  2557. * @param result defines the target vector
  2558. */
  2559. Vector2.FromArrayToRef = function (array, offset, result) {
  2560. result.x = array[offset];
  2561. result.y = array[offset + 1];
  2562. };
  2563. /**
  2564. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2565. * @param value1 defines 1st point of control
  2566. * @param value2 defines 2nd point of control
  2567. * @param value3 defines 3rd point of control
  2568. * @param value4 defines 4th point of control
  2569. * @param amount defines the interpolation factor
  2570. * @returns a new Vector2
  2571. */
  2572. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2573. var squared = amount * amount;
  2574. var cubed = amount * squared;
  2575. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2576. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2577. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2578. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2579. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2580. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2581. return new Vector2(x, y);
  2582. };
  2583. /**
  2584. * 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".
  2585. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2586. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2587. * @param value defines the value to clamp
  2588. * @param min defines the lower limit
  2589. * @param max defines the upper limit
  2590. * @returns a new Vector2
  2591. */
  2592. Vector2.Clamp = function (value, min, max) {
  2593. var x = value.x;
  2594. x = (x > max.x) ? max.x : x;
  2595. x = (x < min.x) ? min.x : x;
  2596. var y = value.y;
  2597. y = (y > max.y) ? max.y : y;
  2598. y = (y < min.y) ? min.y : y;
  2599. return new Vector2(x, y);
  2600. };
  2601. /**
  2602. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2603. * @param value1 defines the 1st control point
  2604. * @param tangent1 defines the outgoing tangent
  2605. * @param value2 defines the 2nd control point
  2606. * @param tangent2 defines the incoming tangent
  2607. * @param amount defines the interpolation factor
  2608. * @returns a new Vector2
  2609. */
  2610. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2611. var squared = amount * amount;
  2612. var cubed = amount * squared;
  2613. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2614. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2615. var part3 = (cubed - (2.0 * squared)) + amount;
  2616. var part4 = cubed - squared;
  2617. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2618. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2619. return new Vector2(x, y);
  2620. };
  2621. /**
  2622. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2623. * @param start defines the start vector
  2624. * @param end defines the end vector
  2625. * @param amount defines the interpolation factor
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Lerp = function (start, end, amount) {
  2629. var x = start.x + ((end.x - start.x) * amount);
  2630. var y = start.y + ((end.y - start.y) * amount);
  2631. return new Vector2(x, y);
  2632. };
  2633. /**
  2634. * Gets the dot product of the vector "left" and the vector "right"
  2635. * @param left defines first vector
  2636. * @param right defines second vector
  2637. * @returns the dot product (float)
  2638. */
  2639. Vector2.Dot = function (left, right) {
  2640. return left.x * right.x + left.y * right.y;
  2641. };
  2642. /**
  2643. * Returns a new Vector2 equal to the normalized given vector
  2644. * @param vector defines the vector to normalize
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.Normalize = function (vector) {
  2648. var newVector = vector.clone();
  2649. newVector.normalize();
  2650. return newVector;
  2651. };
  2652. /**
  2653. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2654. * @param left defines 1st vector
  2655. * @param right defines 2nd vector
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Minimize = function (left, right) {
  2659. var x = (left.x < right.x) ? left.x : right.x;
  2660. var y = (left.y < right.y) ? left.y : right.y;
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2665. * @param left defines 1st vector
  2666. * @param right defines 2nd vector
  2667. * @returns a new Vector2
  2668. */
  2669. Vector2.Maximize = function (left, right) {
  2670. var x = (left.x > right.x) ? left.x : right.x;
  2671. var y = (left.y > right.y) ? left.y : right.y;
  2672. return new Vector2(x, y);
  2673. };
  2674. /**
  2675. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2676. * @param vector defines the vector to transform
  2677. * @param transformation defines the matrix to apply
  2678. * @returns a new Vector2
  2679. */
  2680. Vector2.Transform = function (vector, transformation) {
  2681. var r = Vector2.Zero();
  2682. Vector2.TransformToRef(vector, transformation, r);
  2683. return r;
  2684. };
  2685. /**
  2686. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2687. * @param vector defines the vector to transform
  2688. * @param transformation defines the matrix to apply
  2689. * @param result defines the target vector
  2690. */
  2691. Vector2.TransformToRef = function (vector, transformation, result) {
  2692. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2693. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2694. result.x = x;
  2695. result.y = y;
  2696. };
  2697. /**
  2698. * Determines if a given vector is included in a triangle
  2699. * @param p defines the vector to test
  2700. * @param p0 defines 1st triangle point
  2701. * @param p1 defines 2nd triangle point
  2702. * @param p2 defines 3rd triangle point
  2703. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2704. */
  2705. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2706. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2707. var sign = a < 0 ? -1 : 1;
  2708. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2709. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2710. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2711. };
  2712. /**
  2713. * Gets the distance between the vectors "value1" and "value2"
  2714. * @param value1 defines first vector
  2715. * @param value2 defines second vector
  2716. * @returns the distance between vectors
  2717. */
  2718. Vector2.Distance = function (value1, value2) {
  2719. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2720. };
  2721. /**
  2722. * Returns the squared distance between the vectors "value1" and "value2"
  2723. * @param value1 defines first vector
  2724. * @param value2 defines second vector
  2725. * @returns the squared distance between vectors
  2726. */
  2727. Vector2.DistanceSquared = function (value1, value2) {
  2728. var x = value1.x - value2.x;
  2729. var y = value1.y - value2.y;
  2730. return (x * x) + (y * y);
  2731. };
  2732. /**
  2733. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2734. * @param value1 defines first vector
  2735. * @param value2 defines second vector
  2736. * @returns a new Vector2
  2737. */
  2738. Vector2.Center = function (value1, value2) {
  2739. var center = value1.add(value2);
  2740. center.scaleInPlace(0.5);
  2741. return center;
  2742. };
  2743. /**
  2744. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2745. * @param p defines the middle point
  2746. * @param segA defines one point of the segment
  2747. * @param segB defines the other point of the segment
  2748. * @returns the shortest distance
  2749. */
  2750. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2751. var l2 = Vector2.DistanceSquared(segA, segB);
  2752. if (l2 === 0.0) {
  2753. return Vector2.Distance(p, segA);
  2754. }
  2755. var v = segB.subtract(segA);
  2756. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2757. var proj = segA.add(v.multiplyByFloats(t, t));
  2758. return Vector2.Distance(p, proj);
  2759. };
  2760. return Vector2;
  2761. }());
  2762. BABYLON.Vector2 = Vector2;
  2763. /**
  2764. * Classed used to store (x,y,z) vector representation
  2765. * A Vector3 is the main object used in 3D geometry
  2766. * It can represent etiher the coordinates of a point the space, either a direction
  2767. * Reminder: Babylon.js uses a left handed forward facing system
  2768. */
  2769. var Vector3 = /** @class */ (function () {
  2770. /**
  2771. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2772. * @param x defines the first coordinates (on X axis)
  2773. * @param y defines the second coordinates (on Y axis)
  2774. * @param z defines the third coordinates (on Z axis)
  2775. */
  2776. function Vector3(
  2777. /**
  2778. * Defines the first coordinates (on X axis)
  2779. */
  2780. x,
  2781. /**
  2782. * Defines the second coordinates (on Y axis)
  2783. */
  2784. y,
  2785. /**
  2786. * Defines the third coordinates (on Z axis)
  2787. */
  2788. z) {
  2789. this.x = x;
  2790. this.y = y;
  2791. this.z = z;
  2792. }
  2793. /**
  2794. * Creates a string representation of the Vector3
  2795. * @returns a string with the Vector3 coordinates.
  2796. */
  2797. Vector3.prototype.toString = function () {
  2798. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2799. };
  2800. /**
  2801. * Gets the class name
  2802. * @returns the string "Vector3"
  2803. */
  2804. Vector3.prototype.getClassName = function () {
  2805. return "Vector3";
  2806. };
  2807. /**
  2808. * Creates the Vector3 hash code
  2809. * @returns a number which tends to be unique between Vector3 instances
  2810. */
  2811. Vector3.prototype.getHashCode = function () {
  2812. var hash = this.x || 0;
  2813. hash = (hash * 397) ^ (this.y || 0);
  2814. hash = (hash * 397) ^ (this.z || 0);
  2815. return hash;
  2816. };
  2817. // Operators
  2818. /**
  2819. * Creates an array containing three elements : the coordinates of the Vector3
  2820. * @returns a new array of numbers
  2821. */
  2822. Vector3.prototype.asArray = function () {
  2823. var result = [];
  2824. this.toArray(result, 0);
  2825. return result;
  2826. };
  2827. /**
  2828. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2829. * @param array defines the destination array
  2830. * @param index defines the offset in the destination array
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.toArray = function (array, index) {
  2834. if (index === void 0) { index = 0; }
  2835. array[index] = this.x;
  2836. array[index + 1] = this.y;
  2837. array[index + 2] = this.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2842. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2843. */
  2844. Vector3.prototype.toQuaternion = function () {
  2845. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2846. };
  2847. /**
  2848. * Adds the given vector to the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.addInPlace = function (otherVector) {
  2853. this.x += otherVector.x;
  2854. this.y += otherVector.y;
  2855. this.z += otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.add = function (otherVector) {
  2864. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2865. };
  2866. /**
  2867. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.addToRef = function (otherVector, result) {
  2873. result.x = this.x + otherVector.x;
  2874. result.y = this.y + otherVector.y;
  2875. result.z = this.z + otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Subtract the given vector from the current Vector3
  2880. * @param otherVector defines the second operand
  2881. * @returns the current updated Vector3
  2882. */
  2883. Vector3.prototype.subtractInPlace = function (otherVector) {
  2884. this.x -= otherVector.x;
  2885. this.y -= otherVector.y;
  2886. this.z -= otherVector.z;
  2887. return this;
  2888. };
  2889. /**
  2890. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtract = function (otherVector) {
  2895. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2896. };
  2897. /**
  2898. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2899. * @param otherVector defines the second operand
  2900. * @param result defines the Vector3 object where to store the result
  2901. * @returns the current Vector3
  2902. */
  2903. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2904. result.x = this.x - otherVector.x;
  2905. result.y = this.y - otherVector.y;
  2906. result.z = this.z - otherVector.z;
  2907. return this;
  2908. };
  2909. /**
  2910. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2911. * @param x defines the x coordinate of the operand
  2912. * @param y defines the y coordinate of the operand
  2913. * @param z defines the z coordinate of the operand
  2914. * @returns the resulting Vector3
  2915. */
  2916. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2917. return new Vector3(this.x - x, this.y - y, this.z - z);
  2918. };
  2919. /**
  2920. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2921. * @param x defines the x coordinate of the operand
  2922. * @param y defines the y coordinate of the operand
  2923. * @param z defines the z coordinate of the operand
  2924. * @param result defines the Vector3 object where to store the result
  2925. * @returns the current Vector3
  2926. */
  2927. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2928. result.x = this.x - x;
  2929. result.y = this.y - y;
  2930. result.z = this.z - z;
  2931. return this;
  2932. };
  2933. /**
  2934. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2935. * @returns a new Vector3
  2936. */
  2937. Vector3.prototype.negate = function () {
  2938. return new Vector3(-this.x, -this.y, -this.z);
  2939. };
  2940. /**
  2941. * Multiplies the Vector3 coordinates by the float "scale"
  2942. * @param scale defines the multiplier factor
  2943. * @returns the current updated Vector3
  2944. */
  2945. Vector3.prototype.scaleInPlace = function (scale) {
  2946. this.x *= scale;
  2947. this.y *= scale;
  2948. this.z *= scale;
  2949. return this;
  2950. };
  2951. /**
  2952. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2953. * @param scale defines the multiplier factor
  2954. * @returns a new Vector3
  2955. */
  2956. Vector3.prototype.scale = function (scale) {
  2957. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2958. };
  2959. /**
  2960. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2961. * @param scale defines the multiplier factor
  2962. * @param result defines the Vector3 object where to store the result
  2963. * @returns the current Vector3
  2964. */
  2965. Vector3.prototype.scaleToRef = function (scale, result) {
  2966. result.x = this.x * scale;
  2967. result.y = this.y * scale;
  2968. result.z = this.z * scale;
  2969. return this;
  2970. };
  2971. /**
  2972. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2973. * @param scale defines the scale factor
  2974. * @param result defines the Vector3 object where to store the result
  2975. * @returns the unmodified current Vector3
  2976. */
  2977. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2978. result.x += this.x * scale;
  2979. result.y += this.y * scale;
  2980. result.z += this.z * scale;
  2981. return this;
  2982. };
  2983. /**
  2984. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2985. * @param otherVector defines the second operand
  2986. * @returns true if both vectors are equals
  2987. */
  2988. Vector3.prototype.equals = function (otherVector) {
  2989. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2990. };
  2991. /**
  2992. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2993. * @param otherVector defines the second operand
  2994. * @param epsilon defines the minimal distance to define values as equals
  2995. * @returns true if both vectors are distant less than epsilon
  2996. */
  2997. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2998. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2999. 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);
  3000. };
  3001. /**
  3002. * Returns true if the current Vector3 coordinates equals the given floats
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @returns true if both vectors are equals
  3007. */
  3008. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3009. return this.x === x && this.y === y && this.z === z;
  3010. };
  3011. /**
  3012. * Multiplies the current Vector3 coordinates by the given ones
  3013. * @param otherVector defines the second operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3017. this.x *= otherVector.x;
  3018. this.y *= otherVector.y;
  3019. this.z *= otherVector.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3024. * @param otherVector defines the second operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiply = function (otherVector) {
  3028. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3029. };
  3030. /**
  3031. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3032. * @param otherVector defines the second operand
  3033. * @param result defines the Vector3 object where to store the result
  3034. * @returns the current Vector3
  3035. */
  3036. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3037. result.x = this.x * otherVector.x;
  3038. result.y = this.y * otherVector.y;
  3039. result.z = this.z * otherVector.z;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3044. * @param x defines the x coordinate of the operand
  3045. * @param y defines the y coordinate of the operand
  3046. * @param z defines the z coordinate of the operand
  3047. * @returns the new Vector3
  3048. */
  3049. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3050. return new Vector3(this.x * x, this.y * y, this.z * z);
  3051. };
  3052. /**
  3053. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3054. * @param otherVector defines the second operand
  3055. * @returns the new Vector3
  3056. */
  3057. Vector3.prototype.divide = function (otherVector) {
  3058. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3059. };
  3060. /**
  3061. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3062. * @param otherVector defines the second operand
  3063. * @param result defines the Vector3 object where to store the result
  3064. * @returns the current Vector3
  3065. */
  3066. Vector3.prototype.divideToRef = function (otherVector, result) {
  3067. result.x = this.x / otherVector.x;
  3068. result.y = this.y / otherVector.y;
  3069. result.z = this.z / otherVector.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Divides the current Vector3 coordinates by the given ones.
  3074. * @param otherVector defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.divideInPlace = function (otherVector) {
  3078. return this.divideToRef(otherVector, this);
  3079. };
  3080. /**
  3081. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3082. * @param other defines the second operand
  3083. * @returns the current updated Vector3
  3084. */
  3085. Vector3.prototype.minimizeInPlace = function (other) {
  3086. if (other.x < this.x)
  3087. this.x = other.x;
  3088. if (other.y < this.y)
  3089. this.y = other.y;
  3090. if (other.z < this.z)
  3091. this.z = other.z;
  3092. return this;
  3093. };
  3094. /**
  3095. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3096. * @param other defines the second operand
  3097. * @returns the current updated Vector3
  3098. */
  3099. Vector3.prototype.maximizeInPlace = function (other) {
  3100. if (other.x > this.x)
  3101. this.x = other.x;
  3102. if (other.y > this.y)
  3103. this.y = other.y;
  3104. if (other.z > this.z)
  3105. this.z = other.z;
  3106. return this;
  3107. };
  3108. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3109. /**
  3110. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3111. */
  3112. get: function () {
  3113. var absX = Math.abs(this.x);
  3114. var absY = Math.abs(this.y);
  3115. if (absX !== absY) {
  3116. return true;
  3117. }
  3118. var absZ = Math.abs(this.z);
  3119. if (absX !== absZ) {
  3120. return true;
  3121. }
  3122. if (absY !== absZ) {
  3123. return true;
  3124. }
  3125. return false;
  3126. },
  3127. enumerable: true,
  3128. configurable: true
  3129. });
  3130. // Properties
  3131. /**
  3132. * Gets the length of the Vector3
  3133. * @returns the length of the Vecto3
  3134. */
  3135. Vector3.prototype.length = function () {
  3136. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3137. };
  3138. /**
  3139. * Gets the squared length of the Vector3
  3140. * @returns squared length of the Vector3
  3141. */
  3142. Vector3.prototype.lengthSquared = function () {
  3143. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3144. };
  3145. /**
  3146. * Normalize the current Vector3.
  3147. * Please note that this is an in place operation.
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.normalize = function () {
  3151. var len = this.length();
  3152. if (len === 0 || len === 1.0)
  3153. return this;
  3154. var num = 1.0 / len;
  3155. this.x *= num;
  3156. this.y *= num;
  3157. this.z *= num;
  3158. return this;
  3159. };
  3160. /**
  3161. * Normalize the current Vector3 to a new vector
  3162. * @returns the new Vector3
  3163. */
  3164. Vector3.prototype.normalizeToNew = function () {
  3165. var normalized = new Vector3(0, 0, 0);
  3166. this.normalizeToRef(normalized);
  3167. return normalized;
  3168. };
  3169. /**
  3170. * Normalize the current Vector3 to the reference
  3171. * @param reference define the Vector3 to update
  3172. * @returns the updated Vector3
  3173. */
  3174. Vector3.prototype.normalizeToRef = function (reference) {
  3175. var len = this.length();
  3176. if (len === 0 || len === 1.0) {
  3177. reference.set(this.x, this.y, this.z);
  3178. return reference;
  3179. }
  3180. var scale = 1.0 / len;
  3181. this.scaleToRef(scale, reference);
  3182. return reference;
  3183. };
  3184. /**
  3185. * Creates a new Vector3 copied from the current Vector3
  3186. * @returns the new Vector3
  3187. */
  3188. Vector3.prototype.clone = function () {
  3189. return new Vector3(this.x, this.y, this.z);
  3190. };
  3191. /**
  3192. * Copies the given vector coordinates to the current Vector3 ones
  3193. * @param source defines the source Vector3
  3194. * @returns the current updated Vector3
  3195. */
  3196. Vector3.prototype.copyFrom = function (source) {
  3197. this.x = source.x;
  3198. this.y = source.y;
  3199. this.z = source.z;
  3200. return this;
  3201. };
  3202. /**
  3203. * Copies the given floats to the current Vector3 coordinates
  3204. * @param x defines the x coordinate of the operand
  3205. * @param y defines the y coordinate of the operand
  3206. * @param z defines the z coordinate of the operand
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3210. this.x = x;
  3211. this.y = y;
  3212. this.z = z;
  3213. return this;
  3214. };
  3215. /**
  3216. * Copies the given floats to the current Vector3 coordinates
  3217. * @param x defines the x coordinate of the operand
  3218. * @param y defines the y coordinate of the operand
  3219. * @param z defines the z coordinate of the operand
  3220. * @returns the current updated Vector3
  3221. */
  3222. Vector3.prototype.set = function (x, y, z) {
  3223. return this.copyFromFloats(x, y, z);
  3224. };
  3225. // Statics
  3226. /**
  3227. * Get the clip factor between two vectors
  3228. * @param vector0 defines the first operand
  3229. * @param vector1 defines the second operand
  3230. * @param axis defines the axis to use
  3231. * @param size defines the size along the axis
  3232. * @returns the clip factor
  3233. */
  3234. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3235. var d0 = Vector3.Dot(vector0, axis) - size;
  3236. var d1 = Vector3.Dot(vector1, axis) - size;
  3237. var s = d0 / (d0 - d1);
  3238. return s;
  3239. };
  3240. /**
  3241. * Get angle between two vectors
  3242. * @param vector0 angle between vector0 and vector1
  3243. * @param vector1 angle between vector0 and vector1
  3244. * @param normal direction of the normal
  3245. * @return the angle between vector0 and vector1
  3246. */
  3247. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3248. var v0 = vector0.clone().normalize();
  3249. var v1 = vector1.clone().normalize();
  3250. var dot = Vector3.Dot(v0, v1);
  3251. var n = Vector3.Cross(v0, v1);
  3252. if (Vector3.Dot(n, normal) > 0) {
  3253. return Math.acos(dot);
  3254. }
  3255. return -Math.acos(dot);
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @returns the new Vector3
  3262. */
  3263. Vector3.FromArray = function (array, offset) {
  3264. if (!offset) {
  3265. offset = 0;
  3266. }
  3267. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3268. };
  3269. /**
  3270. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3271. * This function is deprecated. Use FromArray instead
  3272. * @param array defines the source array
  3273. * @param offset defines the offset in the source array
  3274. * @returns the new Vector3
  3275. */
  3276. Vector3.FromFloatArray = function (array, offset) {
  3277. return Vector3.FromArray(array, offset);
  3278. };
  3279. /**
  3280. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3281. * @param array defines the source array
  3282. * @param offset defines the offset in the source array
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. };
  3290. /**
  3291. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3292. * This function is deprecated. Use FromArrayToRef instead.
  3293. * @param array defines the source array
  3294. * @param offset defines the offset in the source array
  3295. * @param result defines the Vector3 where to store the result
  3296. */
  3297. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3298. return Vector3.FromArrayToRef(array, offset, result);
  3299. };
  3300. /**
  3301. * Sets the given vector "result" with the given floats.
  3302. * @param x defines the x coordinate of the source
  3303. * @param y defines the y coordinate of the source
  3304. * @param z defines the z coordinate of the source
  3305. * @param result defines the Vector3 where to store the result
  3306. */
  3307. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3308. result.x = x;
  3309. result.y = y;
  3310. result.z = z;
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3314. * @returns a new empty Vector3
  3315. */
  3316. Vector3.Zero = function () {
  3317. return new Vector3(0.0, 0.0, 0.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3321. * @returns a new unit Vector3
  3322. */
  3323. Vector3.One = function () {
  3324. return new Vector3(1.0, 1.0, 1.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3328. * @returns a new up Vector3
  3329. */
  3330. Vector3.Up = function () {
  3331. return new Vector3(0.0, 1.0, 0.0);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3335. * @returns a new forward Vector3
  3336. */
  3337. Vector3.Forward = function () {
  3338. return new Vector3(0.0, 0.0, 1.0);
  3339. };
  3340. /**
  3341. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3342. * @returns a new right Vector3
  3343. */
  3344. Vector3.Right = function () {
  3345. return new Vector3(1.0, 0.0, 0.0);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3349. * @returns a new left Vector3
  3350. */
  3351. Vector3.Left = function () {
  3352. return new Vector3(-1.0, 0.0, 0.0);
  3353. };
  3354. /**
  3355. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3356. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3357. * @param vector defines the Vector3 to transform
  3358. * @param transformation defines the transformation matrix
  3359. * @returns the transformed Vector3
  3360. */
  3361. Vector3.TransformCoordinates = function (vector, transformation) {
  3362. var result = Vector3.Zero();
  3363. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3364. return result;
  3365. };
  3366. /**
  3367. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3368. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3374. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3375. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3376. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3377. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3378. result.x = x / w;
  3379. result.y = y / w;
  3380. result.z = z / w;
  3381. };
  3382. /**
  3383. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3384. * This method computes tranformed coordinates only, not transformed direction vectors
  3385. * @param x define the x coordinate of the source vector
  3386. * @param y define the y coordinate of the source vector
  3387. * @param z define the z coordinate of the source vector
  3388. * @param transformation defines the transformation matrix
  3389. * @param result defines the Vector3 where to store the result
  3390. */
  3391. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3392. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3393. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3394. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3395. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3396. result.x = rx / rw;
  3397. result.y = ry / rw;
  3398. result.z = rz / rw;
  3399. };
  3400. /**
  3401. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3402. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3403. * @param vector defines the Vector3 to transform
  3404. * @param transformation defines the transformation matrix
  3405. * @returns the new Vector3
  3406. */
  3407. Vector3.TransformNormal = function (vector, transformation) {
  3408. var result = Vector3.Zero();
  3409. Vector3.TransformNormalToRef(vector, transformation, result);
  3410. return result;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param vector defines the Vector3 to transform
  3416. * @param transformation defines the transformation matrix
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3420. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3421. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3422. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3423. result.x = x;
  3424. result.y = y;
  3425. result.z = z;
  3426. };
  3427. /**
  3428. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3429. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3430. * @param x define the x coordinate of the source vector
  3431. * @param y define the y coordinate of the source vector
  3432. * @param z define the z coordinate of the source vector
  3433. * @param transformation defines the transformation matrix
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3437. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3438. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3439. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3443. * @param value1 defines the first control point
  3444. * @param value2 defines the second control point
  3445. * @param value3 defines the third control point
  3446. * @param value4 defines the fourth control point
  3447. * @param amount defines the amount on the spline to use
  3448. * @returns the new Vector3
  3449. */
  3450. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3451. var squared = amount * amount;
  3452. var cubed = amount * squared;
  3453. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3454. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3455. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3456. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3457. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3458. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3459. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3460. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3461. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3462. return new Vector3(x, y, z);
  3463. };
  3464. /**
  3465. * 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"
  3466. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3467. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3468. * @param value defines the current value
  3469. * @param min defines the lower range value
  3470. * @param max defines the upper range value
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.Clamp = function (value, min, max) {
  3474. var x = value.x;
  3475. x = (x > max.x) ? max.x : x;
  3476. x = (x < min.x) ? min.x : x;
  3477. var y = value.y;
  3478. y = (y > max.y) ? max.y : y;
  3479. y = (y < min.y) ? min.y : y;
  3480. var z = value.z;
  3481. z = (z > max.z) ? max.z : z;
  3482. z = (z < min.z) ? min.z : z;
  3483. return new Vector3(x, y, z);
  3484. };
  3485. /**
  3486. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3487. * @param value1 defines the first control point
  3488. * @param tangent1 defines the first tangent vector
  3489. * @param value2 defines the second control point
  3490. * @param tangent2 defines the second tangent vector
  3491. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3492. * @returns the new Vector3
  3493. */
  3494. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3495. var squared = amount * amount;
  3496. var cubed = amount * squared;
  3497. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3498. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3499. var part3 = (cubed - (2.0 * squared)) + amount;
  3500. var part4 = cubed - squared;
  3501. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3502. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3503. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3504. return new Vector3(x, y, z);
  3505. };
  3506. /**
  3507. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3508. * @param start defines the start value
  3509. * @param end defines the end value
  3510. * @param amount max defines amount between both (between 0 and 1)
  3511. * @returns the new Vector3
  3512. */
  3513. Vector3.Lerp = function (start, end, amount) {
  3514. var result = new Vector3(0, 0, 0);
  3515. Vector3.LerpToRef(start, end, amount, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3520. * @param start defines the start value
  3521. * @param end defines the end value
  3522. * @param amount max defines amount between both (between 0 and 1)
  3523. * @param result defines the Vector3 where to store the result
  3524. */
  3525. Vector3.LerpToRef = function (start, end, amount, result) {
  3526. result.x = start.x + ((end.x - start.x) * amount);
  3527. result.y = start.y + ((end.y - start.y) * amount);
  3528. result.z = start.z + ((end.z - start.z) * amount);
  3529. };
  3530. /**
  3531. * Returns the dot product (float) between the vectors "left" and "right"
  3532. * @param left defines the left operand
  3533. * @param right defines the right operand
  3534. * @returns the dot product
  3535. */
  3536. Vector3.Dot = function (left, right) {
  3537. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3538. };
  3539. /**
  3540. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3541. * The cross product is then orthogonal to both "left" and "right"
  3542. * @param left defines the left operand
  3543. * @param right defines the right operand
  3544. * @returns the cross product
  3545. */
  3546. Vector3.Cross = function (left, right) {
  3547. var result = Vector3.Zero();
  3548. Vector3.CrossToRef(left, right, result);
  3549. return result;
  3550. };
  3551. /**
  3552. * Sets the given vector "result" with the cross product of "left" and "right"
  3553. * The cross product is then orthogonal to both "left" and "right"
  3554. * @param left defines the left operand
  3555. * @param right defines the right operand
  3556. * @param result defines the Vector3 where to store the result
  3557. */
  3558. Vector3.CrossToRef = function (left, right, result) {
  3559. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3560. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3561. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3562. result.copyFrom(MathTmp.Vector3[0]);
  3563. };
  3564. /**
  3565. * Returns a new Vector3 as the normalization of the given vector
  3566. * @param vector defines the Vector3 to normalize
  3567. * @returns the new Vector3
  3568. */
  3569. Vector3.Normalize = function (vector) {
  3570. var result = Vector3.Zero();
  3571. Vector3.NormalizeToRef(vector, result);
  3572. return result;
  3573. };
  3574. /**
  3575. * Sets the given vector "result" with the normalization of the given first vector
  3576. * @param vector defines the Vector3 to normalize
  3577. * @param result defines the Vector3 where to store the result
  3578. */
  3579. Vector3.NormalizeToRef = function (vector, result) {
  3580. result.copyFrom(vector);
  3581. result.normalize();
  3582. };
  3583. /**
  3584. * Project a Vector3 onto screen space
  3585. * @param vector defines the Vector3 to project
  3586. * @param world defines the world matrix to use
  3587. * @param transform defines the transform (view x projection) matrix to use
  3588. * @param viewport defines the screen viewport to use
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Project = function (vector, world, transform, viewport) {
  3592. var cw = viewport.width;
  3593. var ch = viewport.height;
  3594. var cx = viewport.x;
  3595. var cy = viewport.y;
  3596. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3597. 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);
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.multiplyToRef(viewportMatrix, matrix);
  3601. return Vector3.TransformCoordinates(vector, matrix);
  3602. };
  3603. /**
  3604. * Unproject from screen space to object space
  3605. * @param source defines the screen space Vector3 to use
  3606. * @param viewportWidth defines the current width of the viewport
  3607. * @param viewportHeight defines the current height of the viewport
  3608. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3609. * @param transform defines the transform (view x projection) matrix to use
  3610. * @returns the new Vector3
  3611. */
  3612. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3613. var matrix = MathTmp.Matrix[0];
  3614. world.multiplyToRef(transform, matrix);
  3615. matrix.invert();
  3616. source.x = source.x / viewportWidth * 2 - 1;
  3617. source.y = -(source.y / viewportHeight * 2 - 1);
  3618. var vector = Vector3.TransformCoordinates(source, matrix);
  3619. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3620. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3621. vector = vector.scale(1.0 / num);
  3622. }
  3623. return vector;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3636. var result = Vector3.Zero();
  3637. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Unproject from screen space to object space
  3642. * @param source defines the screen space Vector3 to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3652. };
  3653. /**
  3654. * Unproject from screen space to object space
  3655. * @param sourceX defines the screen space x coordinate to use
  3656. * @param sourceY defines the screen space y coordinate to use
  3657. * @param sourceZ defines the screen space z coordinate to use
  3658. * @param viewportWidth defines the current width of the viewport
  3659. * @param viewportHeight defines the current height of the viewport
  3660. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3661. * @param view defines the view matrix to use
  3662. * @param projection defines the projection matrix to use
  3663. * @param result defines the Vector3 where to store the result
  3664. */
  3665. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3666. var matrix = MathTmp.Matrix[0];
  3667. world.multiplyToRef(view, matrix);
  3668. matrix.multiplyToRef(projection, matrix);
  3669. matrix.invert();
  3670. var screenSource = MathTmp.Vector3[0];
  3671. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3672. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3673. screenSource.z = 2 * sourceZ - 1.0;
  3674. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3675. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3676. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3677. result.scaleInPlace(1.0 / num);
  3678. }
  3679. };
  3680. /**
  3681. * Gets the minimal coordinate values between two Vector3
  3682. * @param left defines the first operand
  3683. * @param right defines the second operand
  3684. * @returns the new Vector3
  3685. */
  3686. Vector3.Minimize = function (left, right) {
  3687. var min = left.clone();
  3688. min.minimizeInPlace(right);
  3689. return min;
  3690. };
  3691. /**
  3692. * Gets the maximal coordinate values between two Vector3
  3693. * @param left defines the first operand
  3694. * @param right defines the second operand
  3695. * @returns the new Vector3
  3696. */
  3697. Vector3.Maximize = function (left, right) {
  3698. var max = left.clone();
  3699. max.maximizeInPlace(right);
  3700. return max;
  3701. };
  3702. /**
  3703. * Returns the distance between the vectors "value1" and "value2"
  3704. * @param value1 defines the first operand
  3705. * @param value2 defines the second operand
  3706. * @returns the distance
  3707. */
  3708. Vector3.Distance = function (value1, value2) {
  3709. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3710. };
  3711. /**
  3712. * Returns the squared distance between the vectors "value1" and "value2"
  3713. * @param value1 defines the first operand
  3714. * @param value2 defines the second operand
  3715. * @returns the squared distance
  3716. */
  3717. Vector3.DistanceSquared = function (value1, value2) {
  3718. var x = value1.x - value2.x;
  3719. var y = value1.y - value2.y;
  3720. var z = value1.z - value2.z;
  3721. return (x * x) + (y * y) + (z * z);
  3722. };
  3723. /**
  3724. * Returns a new Vector3 located at the center between "value1" and "value2"
  3725. * @param value1 defines the first operand
  3726. * @param value2 defines the second operand
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Center = function (value1, value2) {
  3730. var center = value1.add(value2);
  3731. center.scaleInPlace(0.5);
  3732. return center;
  3733. };
  3734. /**
  3735. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3736. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3737. * to something in order to rotate it from its local system to the given target system
  3738. * Note: axis1, axis2 and axis3 are normalized during this operation
  3739. * @param axis1 defines the first axis
  3740. * @param axis2 defines the second axis
  3741. * @param axis3 defines the third axis
  3742. * @returns a new Vector3
  3743. */
  3744. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3745. var rotation = Vector3.Zero();
  3746. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3747. return rotation;
  3748. };
  3749. /**
  3750. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3751. * @param axis1 defines the first axis
  3752. * @param axis2 defines the second axis
  3753. * @param axis3 defines the third axis
  3754. * @param ref defines the Vector3 where to store the result
  3755. */
  3756. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3757. var quat = MathTmp.Quaternion[0];
  3758. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3759. quat.toEulerAnglesToRef(ref);
  3760. };
  3761. return Vector3;
  3762. }());
  3763. BABYLON.Vector3 = Vector3;
  3764. //Vector4 class created for EulerAngle class conversion to Quaternion
  3765. var Vector4 = /** @class */ (function () {
  3766. /**
  3767. * Creates a Vector4 object from the given floats.
  3768. */
  3769. function Vector4(x, y, z, w) {
  3770. this.x = x;
  3771. this.y = y;
  3772. this.z = z;
  3773. this.w = w;
  3774. }
  3775. /**
  3776. * Returns the string with the Vector4 coordinates.
  3777. */
  3778. Vector4.prototype.toString = function () {
  3779. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3780. };
  3781. /**
  3782. * Returns the string "Vector4".
  3783. */
  3784. Vector4.prototype.getClassName = function () {
  3785. return "Vector4";
  3786. };
  3787. /**
  3788. * Returns the Vector4 hash code.
  3789. */
  3790. Vector4.prototype.getHashCode = function () {
  3791. var hash = this.x || 0;
  3792. hash = (hash * 397) ^ (this.y || 0);
  3793. hash = (hash * 397) ^ (this.z || 0);
  3794. hash = (hash * 397) ^ (this.w || 0);
  3795. return hash;
  3796. };
  3797. // Operators
  3798. /**
  3799. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3800. */
  3801. Vector4.prototype.asArray = function () {
  3802. var result = new Array();
  3803. this.toArray(result, 0);
  3804. return result;
  3805. };
  3806. /**
  3807. * Populates the given array from the given index with the Vector4 coordinates.
  3808. * Returns the Vector4.
  3809. */
  3810. Vector4.prototype.toArray = function (array, index) {
  3811. if (index === undefined) {
  3812. index = 0;
  3813. }
  3814. array[index] = this.x;
  3815. array[index + 1] = this.y;
  3816. array[index + 2] = this.z;
  3817. array[index + 3] = this.w;
  3818. return this;
  3819. };
  3820. /**
  3821. * Adds the given vector to the current Vector4.
  3822. * Returns the updated Vector4.
  3823. */
  3824. Vector4.prototype.addInPlace = function (otherVector) {
  3825. this.x += otherVector.x;
  3826. this.y += otherVector.y;
  3827. this.z += otherVector.z;
  3828. this.w += otherVector.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3833. */
  3834. Vector4.prototype.add = function (otherVector) {
  3835. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3836. };
  3837. /**
  3838. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3839. * Returns the current Vector4.
  3840. */
  3841. Vector4.prototype.addToRef = function (otherVector, result) {
  3842. result.x = this.x + otherVector.x;
  3843. result.y = this.y + otherVector.y;
  3844. result.z = this.z + otherVector.z;
  3845. result.w = this.w + otherVector.w;
  3846. return this;
  3847. };
  3848. /**
  3849. * Subtract in place the given vector from the current Vector4.
  3850. * Returns the updated Vector4.
  3851. */
  3852. Vector4.prototype.subtractInPlace = function (otherVector) {
  3853. this.x -= otherVector.x;
  3854. this.y -= otherVector.y;
  3855. this.z -= otherVector.z;
  3856. this.w -= otherVector.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3861. */
  3862. Vector4.prototype.subtract = function (otherVector) {
  3863. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3864. };
  3865. /**
  3866. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3870. result.x = this.x - otherVector.x;
  3871. result.y = this.y - otherVector.y;
  3872. result.z = this.z - otherVector.z;
  3873. result.w = this.w - otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3878. */
  3879. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3880. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3881. };
  3882. /**
  3883. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3884. * Returns the current Vector4.
  3885. */
  3886. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3887. result.x = this.x - x;
  3888. result.y = this.y - y;
  3889. result.z = this.z - z;
  3890. result.w = this.w - w;
  3891. return this;
  3892. };
  3893. /**
  3894. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3895. */
  3896. Vector4.prototype.negate = function () {
  3897. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3898. };
  3899. /**
  3900. * Multiplies the current Vector4 coordinates by scale (float).
  3901. * Returns the updated Vector4.
  3902. */
  3903. Vector4.prototype.scaleInPlace = function (scale) {
  3904. this.x *= scale;
  3905. this.y *= scale;
  3906. this.z *= scale;
  3907. this.w *= scale;
  3908. return this;
  3909. };
  3910. /**
  3911. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3912. */
  3913. Vector4.prototype.scale = function (scale) {
  3914. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3915. };
  3916. /**
  3917. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3918. * Returns the current Vector4.
  3919. */
  3920. Vector4.prototype.scaleToRef = function (scale, result) {
  3921. result.x = this.x * scale;
  3922. result.y = this.y * scale;
  3923. result.z = this.z * scale;
  3924. result.w = this.w * scale;
  3925. return this;
  3926. };
  3927. /**
  3928. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3929. * @param scale defines the scale factor
  3930. * @param result defines the Vector4 object where to store the result
  3931. * @returns the unmodified current Vector4
  3932. */
  3933. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3934. result.x += this.x * scale;
  3935. result.y += this.y * scale;
  3936. result.z += this.z * scale;
  3937. result.w += this.w * scale;
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3942. */
  3943. Vector4.prototype.equals = function (otherVector) {
  3944. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3945. };
  3946. /**
  3947. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3948. */
  3949. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3950. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3951. return otherVector
  3952. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3953. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3954. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3955. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3956. };
  3957. /**
  3958. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3959. */
  3960. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3961. return this.x === x && this.y === y && this.z === z && this.w === w;
  3962. };
  3963. /**
  3964. * Multiplies in place the current Vector4 by the given one.
  3965. * Returns the updated Vector4.
  3966. */
  3967. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3968. this.x *= otherVector.x;
  3969. this.y *= otherVector.y;
  3970. this.z *= otherVector.z;
  3971. this.w *= otherVector.w;
  3972. return this;
  3973. };
  3974. /**
  3975. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3976. */
  3977. Vector4.prototype.multiply = function (otherVector) {
  3978. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3979. };
  3980. /**
  3981. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3982. * Returns the current Vector4.
  3983. */
  3984. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3985. result.x = this.x * otherVector.x;
  3986. result.y = this.y * otherVector.y;
  3987. result.z = this.z * otherVector.z;
  3988. result.w = this.w * otherVector.w;
  3989. return this;
  3990. };
  3991. /**
  3992. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3993. */
  3994. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3995. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3996. };
  3997. /**
  3998. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3999. */
  4000. Vector4.prototype.divide = function (otherVector) {
  4001. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4002. };
  4003. /**
  4004. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4005. * Returns the current Vector4.
  4006. */
  4007. Vector4.prototype.divideToRef = function (otherVector, result) {
  4008. result.x = this.x / otherVector.x;
  4009. result.y = this.y / otherVector.y;
  4010. result.z = this.z / otherVector.z;
  4011. result.w = this.w / otherVector.w;
  4012. return this;
  4013. };
  4014. /**
  4015. * Divides the current Vector3 coordinates by the given ones.
  4016. * @returns the updated Vector3.
  4017. */
  4018. Vector4.prototype.divideInPlace = function (otherVector) {
  4019. return this.divideToRef(otherVector, this);
  4020. };
  4021. /**
  4022. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4023. * @param other defines the second operand
  4024. * @returns the current updated Vector4
  4025. */
  4026. Vector4.prototype.minimizeInPlace = function (other) {
  4027. if (other.x < this.x)
  4028. this.x = other.x;
  4029. if (other.y < this.y)
  4030. this.y = other.y;
  4031. if (other.z < this.z)
  4032. this.z = other.z;
  4033. if (other.w < this.w)
  4034. this.w = other.w;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4039. * @param other defines the second operand
  4040. * @returns the current updated Vector4
  4041. */
  4042. Vector4.prototype.maximizeInPlace = function (other) {
  4043. if (other.x > this.x)
  4044. this.x = other.x;
  4045. if (other.y > this.y)
  4046. this.y = other.y;
  4047. if (other.z > this.z)
  4048. this.z = other.z;
  4049. if (other.w > this.w)
  4050. this.w = other.w;
  4051. return this;
  4052. };
  4053. // Properties
  4054. /**
  4055. * Returns the Vector4 length (float).
  4056. */
  4057. Vector4.prototype.length = function () {
  4058. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4059. };
  4060. /**
  4061. * Returns the Vector4 squared length (float).
  4062. */
  4063. Vector4.prototype.lengthSquared = function () {
  4064. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4065. };
  4066. // Methods
  4067. /**
  4068. * Normalizes in place the Vector4.
  4069. * Returns the updated Vector4.
  4070. */
  4071. Vector4.prototype.normalize = function () {
  4072. var len = this.length();
  4073. if (len === 0)
  4074. return this;
  4075. var num = 1.0 / len;
  4076. this.x *= num;
  4077. this.y *= num;
  4078. this.z *= num;
  4079. this.w *= num;
  4080. return this;
  4081. };
  4082. /**
  4083. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4084. */
  4085. Vector4.prototype.toVector3 = function () {
  4086. return new Vector3(this.x, this.y, this.z);
  4087. };
  4088. /**
  4089. * Returns a new Vector4 copied from the current one.
  4090. */
  4091. Vector4.prototype.clone = function () {
  4092. return new Vector4(this.x, this.y, this.z, this.w);
  4093. };
  4094. /**
  4095. * Updates the current Vector4 with the given one coordinates.
  4096. * Returns the updated Vector4.
  4097. */
  4098. Vector4.prototype.copyFrom = function (source) {
  4099. this.x = source.x;
  4100. this.y = source.y;
  4101. this.z = source.z;
  4102. this.w = source.w;
  4103. return this;
  4104. };
  4105. /**
  4106. * Updates the current Vector4 coordinates with the given floats.
  4107. * Returns the updated Vector4.
  4108. */
  4109. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4110. this.x = x;
  4111. this.y = y;
  4112. this.z = z;
  4113. this.w = w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the current Vector4 coordinates with the given floats.
  4118. * Returns the updated Vector4.
  4119. */
  4120. Vector4.prototype.set = function (x, y, z, w) {
  4121. return this.copyFromFloats(x, y, z, w);
  4122. };
  4123. // Statics
  4124. /**
  4125. * Returns a new Vector4 set from the starting index of the given array.
  4126. */
  4127. Vector4.FromArray = function (array, offset) {
  4128. if (!offset) {
  4129. offset = 0;
  4130. }
  4131. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" from the starting index of the given array.
  4135. */
  4136. Vector4.FromArrayToRef = function (array, offset, result) {
  4137. result.x = array[offset];
  4138. result.y = array[offset + 1];
  4139. result.z = array[offset + 2];
  4140. result.w = array[offset + 3];
  4141. };
  4142. /**
  4143. * Updates the given vector "result" from the starting index of the given Float32Array.
  4144. */
  4145. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4146. Vector4.FromArrayToRef(array, offset, result);
  4147. };
  4148. /**
  4149. * Updates the given vector "result" coordinates from the given floats.
  4150. */
  4151. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4152. result.x = x;
  4153. result.y = y;
  4154. result.z = z;
  4155. result.w = w;
  4156. };
  4157. /**
  4158. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4159. */
  4160. Vector4.Zero = function () {
  4161. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4162. };
  4163. /**
  4164. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4165. */
  4166. Vector4.One = function () {
  4167. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4168. };
  4169. /**
  4170. * Returns a new normalized Vector4 from the given one.
  4171. */
  4172. Vector4.Normalize = function (vector) {
  4173. var result = Vector4.Zero();
  4174. Vector4.NormalizeToRef(vector, result);
  4175. return result;
  4176. };
  4177. /**
  4178. * Updates the given vector "result" from the normalization of the given one.
  4179. */
  4180. Vector4.NormalizeToRef = function (vector, result) {
  4181. result.copyFrom(vector);
  4182. result.normalize();
  4183. };
  4184. Vector4.Minimize = function (left, right) {
  4185. var min = left.clone();
  4186. min.minimizeInPlace(right);
  4187. return min;
  4188. };
  4189. Vector4.Maximize = function (left, right) {
  4190. var max = left.clone();
  4191. max.maximizeInPlace(right);
  4192. return max;
  4193. };
  4194. /**
  4195. * Returns the distance (float) between the vectors "value1" and "value2".
  4196. */
  4197. Vector4.Distance = function (value1, value2) {
  4198. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4199. };
  4200. /**
  4201. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4202. */
  4203. Vector4.DistanceSquared = function (value1, value2) {
  4204. var x = value1.x - value2.x;
  4205. var y = value1.y - value2.y;
  4206. var z = value1.z - value2.z;
  4207. var w = value1.w - value2.w;
  4208. return (x * x) + (y * y) + (z * z) + (w * w);
  4209. };
  4210. /**
  4211. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4212. */
  4213. Vector4.Center = function (value1, value2) {
  4214. var center = value1.add(value2);
  4215. center.scaleInPlace(0.5);
  4216. return center;
  4217. };
  4218. /**
  4219. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4220. * This methods computes transformed normalized direction vectors only.
  4221. */
  4222. Vector4.TransformNormal = function (vector, transformation) {
  4223. var result = Vector4.Zero();
  4224. Vector4.TransformNormalToRef(vector, transformation, result);
  4225. return result;
  4226. };
  4227. /**
  4228. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4229. * This methods computes transformed normalized direction vectors only.
  4230. */
  4231. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4232. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4233. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4234. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4235. result.x = x;
  4236. result.y = y;
  4237. result.z = z;
  4238. result.w = vector.w;
  4239. };
  4240. /**
  4241. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4242. * This methods computes transformed normalized direction vectors only.
  4243. */
  4244. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4245. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4246. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4247. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4248. result.w = w;
  4249. };
  4250. return Vector4;
  4251. }());
  4252. BABYLON.Vector4 = Vector4;
  4253. var Size = /** @class */ (function () {
  4254. /**
  4255. * Creates a Size object from the given width and height (floats).
  4256. */
  4257. function Size(width, height) {
  4258. this.width = width;
  4259. this.height = height;
  4260. }
  4261. // Returns a string with the Size width and height.
  4262. Size.prototype.toString = function () {
  4263. return "{W: " + this.width + ", H: " + this.height + "}";
  4264. };
  4265. /**
  4266. * Returns the string "Size"
  4267. */
  4268. Size.prototype.getClassName = function () {
  4269. return "Size";
  4270. };
  4271. /**
  4272. * Returns the Size hash code.
  4273. */
  4274. Size.prototype.getHashCode = function () {
  4275. var hash = this.width || 0;
  4276. hash = (hash * 397) ^ (this.height || 0);
  4277. return hash;
  4278. };
  4279. /**
  4280. * Updates the current size from the given one.
  4281. * Returns the updated Size.
  4282. */
  4283. Size.prototype.copyFrom = function (src) {
  4284. this.width = src.width;
  4285. this.height = src.height;
  4286. };
  4287. /**
  4288. * Updates in place the current Size from the given floats.
  4289. * Returns the updated Size.
  4290. */
  4291. Size.prototype.copyFromFloats = function (width, height) {
  4292. this.width = width;
  4293. this.height = height;
  4294. return this;
  4295. };
  4296. /**
  4297. * Updates in place the current Size from the given floats.
  4298. * Returns the updated Size.
  4299. */
  4300. Size.prototype.set = function (width, height) {
  4301. return this.copyFromFloats(width, height);
  4302. };
  4303. /**
  4304. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4305. */
  4306. Size.prototype.multiplyByFloats = function (w, h) {
  4307. return new Size(this.width * w, this.height * h);
  4308. };
  4309. /**
  4310. * Returns a new Size copied from the given one.
  4311. */
  4312. Size.prototype.clone = function () {
  4313. return new Size(this.width, this.height);
  4314. };
  4315. /**
  4316. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4317. */
  4318. Size.prototype.equals = function (other) {
  4319. if (!other) {
  4320. return false;
  4321. }
  4322. return (this.width === other.width) && (this.height === other.height);
  4323. };
  4324. Object.defineProperty(Size.prototype, "surface", {
  4325. /**
  4326. * Returns the surface of the Size : width * height (float).
  4327. */
  4328. get: function () {
  4329. return this.width * this.height;
  4330. },
  4331. enumerable: true,
  4332. configurable: true
  4333. });
  4334. /**
  4335. * Returns a new Size set to (0.0, 0.0)
  4336. */
  4337. Size.Zero = function () {
  4338. return new Size(0.0, 0.0);
  4339. };
  4340. /**
  4341. * Returns a new Size set as the addition result of the current Size and the given one.
  4342. */
  4343. Size.prototype.add = function (otherSize) {
  4344. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4345. return r;
  4346. };
  4347. /**
  4348. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4349. */
  4350. Size.prototype.subtract = function (otherSize) {
  4351. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4352. return r;
  4353. };
  4354. /**
  4355. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4356. */
  4357. Size.Lerp = function (start, end, amount) {
  4358. var w = start.width + ((end.width - start.width) * amount);
  4359. var h = start.height + ((end.height - start.height) * amount);
  4360. return new Size(w, h);
  4361. };
  4362. return Size;
  4363. }());
  4364. BABYLON.Size = Size;
  4365. /**
  4366. * Class used to store quaternion data
  4367. * @see https://en.wikipedia.org/wiki/Quaternion
  4368. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4369. */
  4370. var Quaternion = /** @class */ (function () {
  4371. /**
  4372. * Creates a new Quaternion from the given floats
  4373. * @param x defines the first component (0 by default)
  4374. * @param y defines the second component (0 by default)
  4375. * @param z defines the third component (0 by default)
  4376. * @param w defines the fourth component (1.0 by default)
  4377. */
  4378. function Quaternion(
  4379. /** defines the first component (0 by default) */
  4380. x,
  4381. /** defines the second component (0 by default) */
  4382. y,
  4383. /** defines the third component (0 by default) */
  4384. z,
  4385. /** defines the fourth component (1.0 by default) */
  4386. w) {
  4387. if (x === void 0) { x = 0.0; }
  4388. if (y === void 0) { y = 0.0; }
  4389. if (z === void 0) { z = 0.0; }
  4390. if (w === void 0) { w = 1.0; }
  4391. this.x = x;
  4392. this.y = y;
  4393. this.z = z;
  4394. this.w = w;
  4395. }
  4396. /**
  4397. * Gets a string representation for the current quaternion
  4398. * @returns a string with the Quaternion coordinates
  4399. */
  4400. Quaternion.prototype.toString = function () {
  4401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4402. };
  4403. /**
  4404. * Gets the class name of the quaternion
  4405. * @returns the string "Quaternion"
  4406. */
  4407. Quaternion.prototype.getClassName = function () {
  4408. return "Quaternion";
  4409. };
  4410. /**
  4411. * Gets a hash code for this quaternion
  4412. * @returns the quaternion hash code
  4413. */
  4414. Quaternion.prototype.getHashCode = function () {
  4415. var hash = this.x || 0;
  4416. hash = (hash * 397) ^ (this.y || 0);
  4417. hash = (hash * 397) ^ (this.z || 0);
  4418. hash = (hash * 397) ^ (this.w || 0);
  4419. return hash;
  4420. };
  4421. /**
  4422. * Copy the quaternion to an array
  4423. * @returns a new array populated with 4 elements from the quaternion coordinates
  4424. */
  4425. Quaternion.prototype.asArray = function () {
  4426. return [this.x, this.y, this.z, this.w];
  4427. };
  4428. /**
  4429. * Check if two quaternions are equals
  4430. * @param otherQuaternion defines the second operand
  4431. * @return true if the current quaternion and the given one coordinates are strictly equals
  4432. */
  4433. Quaternion.prototype.equals = function (otherQuaternion) {
  4434. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4435. };
  4436. /**
  4437. * Clone the current quaternion
  4438. * @returns a new quaternion copied from the current one
  4439. */
  4440. Quaternion.prototype.clone = function () {
  4441. return new Quaternion(this.x, this.y, this.z, this.w);
  4442. };
  4443. /**
  4444. * Copy a quaternion to the current one
  4445. * @param other defines the other quaternion
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFrom = function (other) {
  4449. this.x = other.x;
  4450. this.y = other.y;
  4451. this.z = other.z;
  4452. this.w = other.w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion with the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4464. this.x = x;
  4465. this.y = y;
  4466. this.z = z;
  4467. this.w = w;
  4468. return this;
  4469. };
  4470. /**
  4471. * Updates the current quaternion from the given float coordinates
  4472. * @param x defines the x coordinate
  4473. * @param y defines the y coordinate
  4474. * @param z defines the z coordinate
  4475. * @param w defines the w coordinate
  4476. * @returns the updated current quaternion
  4477. */
  4478. Quaternion.prototype.set = function (x, y, z, w) {
  4479. return this.copyFromFloats(x, y, z, w);
  4480. };
  4481. /**
  4482. * Adds two quaternions
  4483. * @param other defines the second operand
  4484. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4485. */
  4486. Quaternion.prototype.add = function (other) {
  4487. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4488. };
  4489. /**
  4490. * Add a quaternion to the current one
  4491. * @param other defines the quaternion to add
  4492. * @returns the current quaternion
  4493. */
  4494. Quaternion.prototype.addInPlace = function (other) {
  4495. this.x += other.x;
  4496. this.y += other.y;
  4497. this.z += other.z;
  4498. this.w += other.w;
  4499. return this;
  4500. };
  4501. /**
  4502. * Subtract two quaternions
  4503. * @param other defines the second operand
  4504. * @returns a new quaternion as the subtraction result of the given one from the current one
  4505. */
  4506. Quaternion.prototype.subtract = function (other) {
  4507. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4508. };
  4509. /**
  4510. * Multiplies the current quaternion by a scale factor
  4511. * @param value defines the scale factor
  4512. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4513. */
  4514. Quaternion.prototype.scale = function (value) {
  4515. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4516. };
  4517. /**
  4518. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4519. * @param scale defines the scale factor
  4520. * @param result defines the Quaternion object where to store the result
  4521. * @returns the unmodified current quaternion
  4522. */
  4523. Quaternion.prototype.scaleToRef = function (scale, result) {
  4524. result.x = this.x * scale;
  4525. result.y = this.y * scale;
  4526. result.z = this.z * scale;
  4527. result.w = this.w * scale;
  4528. return this;
  4529. };
  4530. /**
  4531. * Multiplies in place the current quaternion by a scale factor
  4532. * @param value defines the scale factor
  4533. * @returns the current modified quaternion
  4534. */
  4535. Quaternion.prototype.scaleInPlace = function (value) {
  4536. this.x *= value;
  4537. this.y *= value;
  4538. this.z *= value;
  4539. this.w *= value;
  4540. return this;
  4541. };
  4542. /**
  4543. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4544. * @param scale defines the scale factor
  4545. * @param result defines the Quaternion object where to store the result
  4546. * @returns the unmodified current quaternion
  4547. */
  4548. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4549. result.x += this.x * scale;
  4550. result.y += this.y * scale;
  4551. result.z += this.z * scale;
  4552. result.w += this.w * scale;
  4553. return this;
  4554. };
  4555. /**
  4556. * Multiplies two quaternions
  4557. * @param q1 defines the second operand
  4558. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4559. */
  4560. Quaternion.prototype.multiply = function (q1) {
  4561. var result = new Quaternion(0, 0, 0, 1.0);
  4562. this.multiplyToRef(q1, result);
  4563. return result;
  4564. };
  4565. /**
  4566. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4567. * @param q1 defines the second operand
  4568. * @param result defines the target quaternion
  4569. * @returns the current quaternion
  4570. */
  4571. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4572. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4573. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4574. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4575. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4576. result.copyFromFloats(x, y, z, w);
  4577. return this;
  4578. };
  4579. /**
  4580. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4581. * @param q1 defines the second operand
  4582. * @returns the currentupdated quaternion
  4583. */
  4584. Quaternion.prototype.multiplyInPlace = function (q1) {
  4585. this.multiplyToRef(q1, this);
  4586. return this;
  4587. };
  4588. /**
  4589. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4590. * @param ref defines the target quaternion
  4591. * @returns the current quaternion
  4592. */
  4593. Quaternion.prototype.conjugateToRef = function (ref) {
  4594. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4595. return this;
  4596. };
  4597. /**
  4598. * Conjugates in place (1-q) the current quaternion
  4599. * @returns the current updated quaternion
  4600. */
  4601. Quaternion.prototype.conjugateInPlace = function () {
  4602. this.x *= -1;
  4603. this.y *= -1;
  4604. this.z *= -1;
  4605. return this;
  4606. };
  4607. /**
  4608. * Conjugates in place (1-q) the current quaternion
  4609. * @returns a new quaternion
  4610. */
  4611. Quaternion.prototype.conjugate = function () {
  4612. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4613. return result;
  4614. };
  4615. /**
  4616. * Gets length of current quaternion
  4617. * @returns the quaternion length (float)
  4618. */
  4619. Quaternion.prototype.length = function () {
  4620. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4621. };
  4622. /**
  4623. * Normalize in place the current quaternion
  4624. * @returns the current updated quaternion
  4625. */
  4626. Quaternion.prototype.normalize = function () {
  4627. var length = 1.0 / this.length();
  4628. this.x *= length;
  4629. this.y *= length;
  4630. this.z *= length;
  4631. this.w *= length;
  4632. return this;
  4633. };
  4634. /**
  4635. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4636. * @param order is a reserved parameter and is ignore for now
  4637. * @returns a new Vector3 containing the Euler angles
  4638. */
  4639. Quaternion.prototype.toEulerAngles = function (order) {
  4640. if (order === void 0) { order = "YZX"; }
  4641. var result = Vector3.Zero();
  4642. this.toEulerAnglesToRef(result, order);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4647. * @param result defines the vector which will be filled with the Euler angles
  4648. * @param order is a reserved parameter and is ignore for now
  4649. * @returns the current unchanged quaternion
  4650. */
  4651. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4652. if (order === void 0) { order = "YZX"; }
  4653. var qz = this.z;
  4654. var qx = this.x;
  4655. var qy = this.y;
  4656. var qw = this.w;
  4657. var sqw = qw * qw;
  4658. var sqz = qz * qz;
  4659. var sqx = qx * qx;
  4660. var sqy = qy * qy;
  4661. var zAxisY = qy * qz - qx * qw;
  4662. var limit = .4999999;
  4663. if (zAxisY < -limit) {
  4664. result.y = 2 * Math.atan2(qy, qw);
  4665. result.x = Math.PI / 2;
  4666. result.z = 0;
  4667. }
  4668. else if (zAxisY > limit) {
  4669. result.y = 2 * Math.atan2(qy, qw);
  4670. result.x = -Math.PI / 2;
  4671. result.z = 0;
  4672. }
  4673. else {
  4674. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4675. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4676. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4677. }
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the given rotation matrix with the current quaternion values
  4682. * @param result defines the target matrix
  4683. * @returns the current unchanged quaternion
  4684. */
  4685. Quaternion.prototype.toRotationMatrix = function (result) {
  4686. var xx = this.x * this.x;
  4687. var yy = this.y * this.y;
  4688. var zz = this.z * this.z;
  4689. var xy = this.x * this.y;
  4690. var zw = this.z * this.w;
  4691. var zx = this.z * this.x;
  4692. var yw = this.y * this.w;
  4693. var yz = this.y * this.z;
  4694. var xw = this.x * this.w;
  4695. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4696. result.m[1] = 2.0 * (xy + zw);
  4697. result.m[2] = 2.0 * (zx - yw);
  4698. result.m[3] = 0;
  4699. result.m[4] = 2.0 * (xy - zw);
  4700. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4701. result.m[6] = 2.0 * (yz + xw);
  4702. result.m[7] = 0;
  4703. result.m[8] = 2.0 * (zx + yw);
  4704. result.m[9] = 2.0 * (yz - xw);
  4705. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4706. result.m[11] = 0;
  4707. result.m[12] = 0;
  4708. result.m[13] = 0;
  4709. result.m[14] = 0;
  4710. result.m[15] = 1.0;
  4711. result._markAsUpdated();
  4712. return this;
  4713. };
  4714. /**
  4715. * Updates the current quaternion from the given rotation matrix values
  4716. * @param matrix defines the source matrix
  4717. * @returns the current updated quaternion
  4718. */
  4719. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4720. Quaternion.FromRotationMatrixToRef(matrix, this);
  4721. return this;
  4722. };
  4723. // Statics
  4724. /**
  4725. * Creates a new quaternion from a rotation matrix
  4726. * @param matrix defines the source matrix
  4727. * @returns a new quaternion created from the given rotation matrix values
  4728. */
  4729. Quaternion.FromRotationMatrix = function (matrix) {
  4730. var result = new Quaternion();
  4731. Quaternion.FromRotationMatrixToRef(matrix, result);
  4732. return result;
  4733. };
  4734. /**
  4735. * Updates the given quaternion with the given rotation matrix values
  4736. * @param matrix defines the source matrix
  4737. * @param result defines the target quaternion
  4738. */
  4739. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4740. var data = matrix.m;
  4741. var m11 = data[0], m12 = data[4], m13 = data[8];
  4742. var m21 = data[1], m22 = data[5], m23 = data[9];
  4743. var m31 = data[2], m32 = data[6], m33 = data[10];
  4744. var trace = m11 + m22 + m33;
  4745. var s;
  4746. if (trace > 0) {
  4747. s = 0.5 / Math.sqrt(trace + 1.0);
  4748. result.w = 0.25 / s;
  4749. result.x = (m32 - m23) * s;
  4750. result.y = (m13 - m31) * s;
  4751. result.z = (m21 - m12) * s;
  4752. }
  4753. else if (m11 > m22 && m11 > m33) {
  4754. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4755. result.w = (m32 - m23) / s;
  4756. result.x = 0.25 * s;
  4757. result.y = (m12 + m21) / s;
  4758. result.z = (m13 + m31) / s;
  4759. }
  4760. else if (m22 > m33) {
  4761. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4762. result.w = (m13 - m31) / s;
  4763. result.x = (m12 + m21) / s;
  4764. result.y = 0.25 * s;
  4765. result.z = (m23 + m32) / s;
  4766. }
  4767. else {
  4768. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4769. result.w = (m21 - m12) / s;
  4770. result.x = (m13 + m31) / s;
  4771. result.y = (m23 + m32) / s;
  4772. result.z = 0.25 * s;
  4773. }
  4774. };
  4775. /**
  4776. * Returns the dot product (float) between the quaternions "left" and "right"
  4777. * @param left defines the left operand
  4778. * @param right defines the right operand
  4779. * @returns the dot product
  4780. */
  4781. Quaternion.Dot = function (left, right) {
  4782. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4783. };
  4784. /**
  4785. * Checks if the two quaternions are close to each other
  4786. * @param quat0 defines the first quaternion to check
  4787. * @param quat1 defines the second quaternion to check
  4788. * @returns true if the two quaternions are close to each other
  4789. */
  4790. Quaternion.AreClose = function (quat0, quat1) {
  4791. var dot = Quaternion.Dot(quat0, quat1);
  4792. return dot >= 0;
  4793. };
  4794. /**
  4795. * Creates an empty quaternion
  4796. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4797. */
  4798. Quaternion.Zero = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4800. };
  4801. /**
  4802. * Inverse a given quaternion
  4803. * @param q defines the source quaternion
  4804. * @returns a new quaternion as the inverted current quaternion
  4805. */
  4806. Quaternion.Inverse = function (q) {
  4807. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4808. };
  4809. /**
  4810. * Creates an identity quaternion
  4811. * @returns the identity quaternion
  4812. */
  4813. Quaternion.Identity = function () {
  4814. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4815. };
  4816. /**
  4817. * Gets a boolean indicating if the given quaternion is identity
  4818. * @param quaternion defines the quaternion to check
  4819. * @returns true if the quaternion is identity
  4820. */
  4821. Quaternion.IsIdentity = function (quaternion) {
  4822. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4823. };
  4824. /**
  4825. * Creates a quaternion from a rotation around an axis
  4826. * @param axis defines the axis to use
  4827. * @param angle defines the angle to use
  4828. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4829. */
  4830. Quaternion.RotationAxis = function (axis, angle) {
  4831. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4832. };
  4833. /**
  4834. * Creates a rotation around an axis and stores it into the given quaternion
  4835. * @param axis defines the axis to use
  4836. * @param angle defines the angle to use
  4837. * @param result defines the target quaternion
  4838. * @returns the target quaternion
  4839. */
  4840. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4841. var sin = Math.sin(angle / 2);
  4842. axis.normalize();
  4843. result.w = Math.cos(angle / 2);
  4844. result.x = axis.x * sin;
  4845. result.y = axis.y * sin;
  4846. result.z = axis.z * sin;
  4847. return result;
  4848. };
  4849. /**
  4850. * Creates a new quaternion from data stored into an array
  4851. * @param array defines the data source
  4852. * @param offset defines the offset in the source array where the data starts
  4853. * @returns a new quaternion
  4854. */
  4855. Quaternion.FromArray = function (array, offset) {
  4856. if (!offset) {
  4857. offset = 0;
  4858. }
  4859. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4860. };
  4861. /**
  4862. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4863. * @param yaw defines the rotation around Y axis
  4864. * @param pitch defines the rotation around X axis
  4865. * @param roll defines the rotation around Z axis
  4866. * @returns the new quaternion
  4867. */
  4868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4869. var q = new Quaternion();
  4870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4871. return q;
  4872. };
  4873. /**
  4874. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4875. * @param yaw defines the rotation around Y axis
  4876. * @param pitch defines the rotation around X axis
  4877. * @param roll defines the rotation around Z axis
  4878. * @param result defines the target quaternion
  4879. */
  4880. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4881. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4882. var halfRoll = roll * 0.5;
  4883. var halfPitch = pitch * 0.5;
  4884. var halfYaw = yaw * 0.5;
  4885. var sinRoll = Math.sin(halfRoll);
  4886. var cosRoll = Math.cos(halfRoll);
  4887. var sinPitch = Math.sin(halfPitch);
  4888. var cosPitch = Math.cos(halfPitch);
  4889. var sinYaw = Math.sin(halfYaw);
  4890. var cosYaw = Math.cos(halfYaw);
  4891. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4892. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4893. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4894. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4895. };
  4896. /**
  4897. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4898. * @param alpha defines the rotation around first axis
  4899. * @param beta defines the rotation around second axis
  4900. * @param gamma defines the rotation around third axis
  4901. * @returns the new quaternion
  4902. */
  4903. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4904. var result = new Quaternion();
  4905. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4906. return result;
  4907. };
  4908. /**
  4909. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4910. * @param alpha defines the rotation around first axis
  4911. * @param beta defines the rotation around second axis
  4912. * @param gamma defines the rotation around third axis
  4913. * @param result defines the target quaternion
  4914. */
  4915. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4916. // Produces a quaternion from Euler angles in the z-x-z orientation
  4917. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4918. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4919. var halfBeta = beta * 0.5;
  4920. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4921. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4922. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4923. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4924. };
  4925. /**
  4926. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4927. * @param axis1 defines the first axis
  4928. * @param axis2 defines the second axis
  4929. * @param axis3 defines the third axis
  4930. * @returns the new quaternion
  4931. */
  4932. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4933. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4934. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4935. return quat;
  4936. };
  4937. /**
  4938. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4939. * @param axis1 defines the first axis
  4940. * @param axis2 defines the second axis
  4941. * @param axis3 defines the third axis
  4942. * @param ref defines the target quaternion
  4943. */
  4944. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4945. var rotMat = MathTmp.Matrix[0];
  4946. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4947. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4948. };
  4949. /**
  4950. * Interpolates between two quaternions
  4951. * @param left defines first quaternion
  4952. * @param right defines second quaternion
  4953. * @param amount defines the gradient to use
  4954. * @returns the new interpolated quaternion
  4955. */
  4956. Quaternion.Slerp = function (left, right, amount) {
  4957. var result = Quaternion.Identity();
  4958. Quaternion.SlerpToRef(left, right, amount, result);
  4959. return result;
  4960. };
  4961. /**
  4962. * Interpolates between two quaternions and stores it into a target quaternion
  4963. * @param left defines first quaternion
  4964. * @param right defines second quaternion
  4965. * @param amount defines the gradient to use
  4966. * @param result defines the target quaternion
  4967. */
  4968. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4969. var num2;
  4970. var num3;
  4971. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4972. var flag = false;
  4973. if (num4 < 0) {
  4974. flag = true;
  4975. num4 = -num4;
  4976. }
  4977. if (num4 > 0.999999) {
  4978. num3 = 1 - amount;
  4979. num2 = flag ? -amount : amount;
  4980. }
  4981. else {
  4982. var num5 = Math.acos(num4);
  4983. var num6 = (1.0 / Math.sin(num5));
  4984. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4985. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4986. }
  4987. result.x = (num3 * left.x) + (num2 * right.x);
  4988. result.y = (num3 * left.y) + (num2 * right.y);
  4989. result.z = (num3 * left.z) + (num2 * right.z);
  4990. result.w = (num3 * left.w) + (num2 * right.w);
  4991. };
  4992. /**
  4993. * Interpolate between two quaternions using Hermite interpolation
  4994. * @param value1 defines first quaternion
  4995. * @param tangent1 defines the incoming tangent
  4996. * @param value2 defines second quaternion
  4997. * @param tangent2 defines the outgoing tangent
  4998. * @param amount defines the target quaternion
  4999. * @returns the new interpolated quaternion
  5000. */
  5001. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5002. var squared = amount * amount;
  5003. var cubed = amount * squared;
  5004. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5005. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5006. var part3 = (cubed - (2.0 * squared)) + amount;
  5007. var part4 = cubed - squared;
  5008. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5009. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5010. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5011. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5012. return new Quaternion(x, y, z, w);
  5013. };
  5014. return Quaternion;
  5015. }());
  5016. BABYLON.Quaternion = Quaternion;
  5017. /**
  5018. * Class used to store matrix data (4x4)
  5019. */
  5020. var Matrix = /** @class */ (function () {
  5021. /**
  5022. * Creates an empty matrix (filled with zeros)
  5023. */
  5024. function Matrix() {
  5025. this._isIdentity = false;
  5026. this._isIdentityDirty = true;
  5027. /**
  5028. * Gets or sets the internal data of the matrix
  5029. */
  5030. this.m = new Float32Array(16);
  5031. this._markAsUpdated();
  5032. }
  5033. /** @hidden */
  5034. Matrix.prototype._markAsUpdated = function () {
  5035. this.updateFlag = Matrix._updateFlagSeed++;
  5036. this._isIdentityDirty = true;
  5037. };
  5038. // Properties
  5039. /**
  5040. * Check if the current matrix is indentity
  5041. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5042. * @returns true is the matrix is the identity matrix
  5043. */
  5044. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5045. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5046. if (this._isIdentityDirty) {
  5047. this._isIdentityDirty = false;
  5048. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5049. this._isIdentity = false;
  5050. }
  5051. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5052. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5053. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5054. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5055. this._isIdentity = false;
  5056. }
  5057. else {
  5058. this._isIdentity = true;
  5059. }
  5060. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5061. this._isIdentity = false;
  5062. }
  5063. }
  5064. return this._isIdentity;
  5065. };
  5066. /**
  5067. * Gets the determinant of the matrix
  5068. * @returns the matrix determinant
  5069. */
  5070. Matrix.prototype.determinant = function () {
  5071. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5072. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5073. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5074. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5075. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5076. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5077. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5078. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5079. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5080. };
  5081. // Methods
  5082. /**
  5083. * Returns the matrix as a Float32Array
  5084. * @returns the matrix underlying array
  5085. */
  5086. Matrix.prototype.toArray = function () {
  5087. return this.m;
  5088. };
  5089. /**
  5090. * Returns the matrix as a Float32Array
  5091. * @returns the matrix underlying array.
  5092. */
  5093. Matrix.prototype.asArray = function () {
  5094. return this.toArray();
  5095. };
  5096. /**
  5097. * Inverts the current matrix in place
  5098. * @returns the current inverted matrix
  5099. */
  5100. Matrix.prototype.invert = function () {
  5101. this.invertToRef(this);
  5102. return this;
  5103. };
  5104. /**
  5105. * Sets all the matrix elements to zero
  5106. * @returns the current matrix
  5107. */
  5108. Matrix.prototype.reset = function () {
  5109. for (var index = 0; index < 16; index++) {
  5110. this.m[index] = 0.0;
  5111. }
  5112. this._markAsUpdated();
  5113. return this;
  5114. };
  5115. /**
  5116. * Adds the current matrix with a second one
  5117. * @param other defines the matrix to add
  5118. * @returns a new matrix as the addition of the current matrix and the given one
  5119. */
  5120. Matrix.prototype.add = function (other) {
  5121. var result = new Matrix();
  5122. this.addToRef(other, result);
  5123. return result;
  5124. };
  5125. /**
  5126. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5127. * @param other defines the matrix to add
  5128. * @param result defines the target matrix
  5129. * @returns the current matrix
  5130. */
  5131. Matrix.prototype.addToRef = function (other, result) {
  5132. for (var index = 0; index < 16; index++) {
  5133. result.m[index] = this.m[index] + other.m[index];
  5134. }
  5135. result._markAsUpdated();
  5136. return this;
  5137. };
  5138. /**
  5139. * Adds in place the given matrix to the current matrix
  5140. * @param other defines the second operand
  5141. * @returns the current updated matrix
  5142. */
  5143. Matrix.prototype.addToSelf = function (other) {
  5144. for (var index = 0; index < 16; index++) {
  5145. this.m[index] += other.m[index];
  5146. }
  5147. this._markAsUpdated();
  5148. return this;
  5149. };
  5150. /**
  5151. * Sets the given matrix to the current inverted Matrix
  5152. * @param other defines the target matrix
  5153. * @returns the unmodified current matrix
  5154. */
  5155. Matrix.prototype.invertToRef = function (other) {
  5156. var l1 = this.m[0];
  5157. var l2 = this.m[1];
  5158. var l3 = this.m[2];
  5159. var l4 = this.m[3];
  5160. var l5 = this.m[4];
  5161. var l6 = this.m[5];
  5162. var l7 = this.m[6];
  5163. var l8 = this.m[7];
  5164. var l9 = this.m[8];
  5165. var l10 = this.m[9];
  5166. var l11 = this.m[10];
  5167. var l12 = this.m[11];
  5168. var l13 = this.m[12];
  5169. var l14 = this.m[13];
  5170. var l15 = this.m[14];
  5171. var l16 = this.m[15];
  5172. var l17 = (l11 * l16) - (l12 * l15);
  5173. var l18 = (l10 * l16) - (l12 * l14);
  5174. var l19 = (l10 * l15) - (l11 * l14);
  5175. var l20 = (l9 * l16) - (l12 * l13);
  5176. var l21 = (l9 * l15) - (l11 * l13);
  5177. var l22 = (l9 * l14) - (l10 * l13);
  5178. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5179. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5180. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5181. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5182. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5183. var l28 = (l7 * l16) - (l8 * l15);
  5184. var l29 = (l6 * l16) - (l8 * l14);
  5185. var l30 = (l6 * l15) - (l7 * l14);
  5186. var l31 = (l5 * l16) - (l8 * l13);
  5187. var l32 = (l5 * l15) - (l7 * l13);
  5188. var l33 = (l5 * l14) - (l6 * l13);
  5189. var l34 = (l7 * l12) - (l8 * l11);
  5190. var l35 = (l6 * l12) - (l8 * l10);
  5191. var l36 = (l6 * l11) - (l7 * l10);
  5192. var l37 = (l5 * l12) - (l8 * l9);
  5193. var l38 = (l5 * l11) - (l7 * l9);
  5194. var l39 = (l5 * l10) - (l6 * l9);
  5195. other.m[0] = l23 * l27;
  5196. other.m[4] = l24 * l27;
  5197. other.m[8] = l25 * l27;
  5198. other.m[12] = l26 * l27;
  5199. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5200. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5201. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5202. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5203. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5204. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5205. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5206. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5207. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5208. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5209. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5210. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5211. other._markAsUpdated();
  5212. return this;
  5213. };
  5214. /**
  5215. * Inserts the translation vector (using 3 floats) in the current matrix
  5216. * @param x defines the 1st component of the translation
  5217. * @param y defines the 2nd component of the translation
  5218. * @param z defines the 3rd component of the translation
  5219. * @returns the current updated matrix
  5220. */
  5221. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5222. this.m[12] = x;
  5223. this.m[13] = y;
  5224. this.m[14] = z;
  5225. this._markAsUpdated();
  5226. return this;
  5227. };
  5228. /**
  5229. * Inserts the translation vector in the current matrix
  5230. * @param vector3 defines the translation to insert
  5231. * @returns the current updated matrix
  5232. */
  5233. Matrix.prototype.setTranslation = function (vector3) {
  5234. this.m[12] = vector3.x;
  5235. this.m[13] = vector3.y;
  5236. this.m[14] = vector3.z;
  5237. this._markAsUpdated();
  5238. return this;
  5239. };
  5240. /**
  5241. * Gets the translation value of the current matrix
  5242. * @returns a new Vector3 as the extracted translation from the matrix
  5243. */
  5244. Matrix.prototype.getTranslation = function () {
  5245. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5246. };
  5247. /**
  5248. * Fill a Vector3 with the extracted translation from the matrix
  5249. * @param result defines the Vector3 where to store the translation
  5250. * @returns the current matrix
  5251. */
  5252. Matrix.prototype.getTranslationToRef = function (result) {
  5253. result.x = this.m[12];
  5254. result.y = this.m[13];
  5255. result.z = this.m[14];
  5256. return this;
  5257. };
  5258. /**
  5259. * Remove rotation and scaling part from the matrix
  5260. * @returns the updated matrix
  5261. */
  5262. Matrix.prototype.removeRotationAndScaling = function () {
  5263. this.setRowFromFloats(0, 1, 0, 0, 0);
  5264. this.setRowFromFloats(1, 0, 1, 0, 0);
  5265. this.setRowFromFloats(2, 0, 0, 1, 0);
  5266. return this;
  5267. };
  5268. /**
  5269. * Multiply two matrices
  5270. * @param other defines the second operand
  5271. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5272. */
  5273. Matrix.prototype.multiply = function (other) {
  5274. var result = new Matrix();
  5275. this.multiplyToRef(other, result);
  5276. return result;
  5277. };
  5278. /**
  5279. * Copy the current matrix from the given one
  5280. * @param other defines the source matrix
  5281. * @returns the current updated matrix
  5282. */
  5283. Matrix.prototype.copyFrom = function (other) {
  5284. for (var index = 0; index < 16; index++) {
  5285. this.m[index] = other.m[index];
  5286. }
  5287. this._markAsUpdated();
  5288. return this;
  5289. };
  5290. /**
  5291. * Populates the given array from the starting index with the current matrix values
  5292. * @param array defines the target array
  5293. * @param offset defines the offset in the target array where to start storing values
  5294. * @returns the current matrix
  5295. */
  5296. Matrix.prototype.copyToArray = function (array, offset) {
  5297. if (offset === void 0) { offset = 0; }
  5298. for (var index = 0; index < 16; index++) {
  5299. array[offset + index] = this.m[index];
  5300. }
  5301. return this;
  5302. };
  5303. /**
  5304. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5305. * @param other defines the second operand
  5306. * @param result defines the matrix where to store the multiplication
  5307. * @returns the current matrix
  5308. */
  5309. Matrix.prototype.multiplyToRef = function (other, result) {
  5310. this.multiplyToArray(other, result.m, 0);
  5311. result._markAsUpdated();
  5312. return this;
  5313. };
  5314. /**
  5315. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5316. * @param other defines the second operand
  5317. * @param result defines the array where to store the multiplication
  5318. * @param offset defines the offset in the target array where to start storing values
  5319. * @returns the current matrix
  5320. */
  5321. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5322. var tm0 = this.m[0];
  5323. var tm1 = this.m[1];
  5324. var tm2 = this.m[2];
  5325. var tm3 = this.m[3];
  5326. var tm4 = this.m[4];
  5327. var tm5 = this.m[5];
  5328. var tm6 = this.m[6];
  5329. var tm7 = this.m[7];
  5330. var tm8 = this.m[8];
  5331. var tm9 = this.m[9];
  5332. var tm10 = this.m[10];
  5333. var tm11 = this.m[11];
  5334. var tm12 = this.m[12];
  5335. var tm13 = this.m[13];
  5336. var tm14 = this.m[14];
  5337. var tm15 = this.m[15];
  5338. var om0 = other.m[0];
  5339. var om1 = other.m[1];
  5340. var om2 = other.m[2];
  5341. var om3 = other.m[3];
  5342. var om4 = other.m[4];
  5343. var om5 = other.m[5];
  5344. var om6 = other.m[6];
  5345. var om7 = other.m[7];
  5346. var om8 = other.m[8];
  5347. var om9 = other.m[9];
  5348. var om10 = other.m[10];
  5349. var om11 = other.m[11];
  5350. var om12 = other.m[12];
  5351. var om13 = other.m[13];
  5352. var om14 = other.m[14];
  5353. var om15 = other.m[15];
  5354. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5355. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5356. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5357. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5358. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5359. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5360. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5361. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5362. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5363. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5364. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5365. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5366. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5367. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5368. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5369. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5370. return this;
  5371. };
  5372. /**
  5373. * Check equality between this matrix and a second one
  5374. * @param value defines the second matrix to compare
  5375. * @returns true is the current matrix and the given one values are strictly equal
  5376. */
  5377. Matrix.prototype.equals = function (value) {
  5378. return value &&
  5379. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5380. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5381. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5382. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5383. };
  5384. /**
  5385. * Clone the current matrix
  5386. * @returns a new matrix from the current matrix
  5387. */
  5388. Matrix.prototype.clone = function () {
  5389. 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]);
  5390. };
  5391. /**
  5392. * Returns the name of the current matrix class
  5393. * @returns the string "Matrix"
  5394. */
  5395. Matrix.prototype.getClassName = function () {
  5396. return "Matrix";
  5397. };
  5398. /**
  5399. * Gets the hash code of the current matrix
  5400. * @returns the hash code
  5401. */
  5402. Matrix.prototype.getHashCode = function () {
  5403. var hash = this.m[0] || 0;
  5404. for (var i = 1; i < 16; i++) {
  5405. hash = (hash * 397) ^ (this.m[i] || 0);
  5406. }
  5407. return hash;
  5408. };
  5409. /**
  5410. * Decomposes the current Matrix into a translation, rotation and scaling components
  5411. * @param scale defines the scale vector3 given as a reference to update
  5412. * @param rotation defines the rotation quaternion given as a reference to update
  5413. * @param translation defines the translation vector3 given as a reference to update
  5414. * @returns true if operation was successful
  5415. */
  5416. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5417. if (translation) {
  5418. translation.x = this.m[12];
  5419. translation.y = this.m[13];
  5420. translation.z = this.m[14];
  5421. }
  5422. scale = scale || MathTmp.Vector3[0];
  5423. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5424. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5425. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5426. if (this.determinant() <= 0) {
  5427. scale.y *= -1;
  5428. }
  5429. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5430. if (rotation) {
  5431. rotation.x = 0;
  5432. rotation.y = 0;
  5433. rotation.z = 0;
  5434. rotation.w = 1;
  5435. }
  5436. return false;
  5437. }
  5438. if (rotation) {
  5439. 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]);
  5440. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5441. }
  5442. return true;
  5443. };
  5444. /**
  5445. * Gets specific row of the matrix
  5446. * @param index defines the number of the row to get
  5447. * @returns the index-th row of the current matrix as a new Vector4
  5448. */
  5449. Matrix.prototype.getRow = function (index) {
  5450. if (index < 0 || index > 3) {
  5451. return null;
  5452. }
  5453. var i = index * 4;
  5454. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5455. };
  5456. /**
  5457. * Sets the index-th row of the current matrix to the vector4 values
  5458. * @param index defines the number of the row to set
  5459. * @param row defines the target vector4
  5460. * @returns the updated current matrix
  5461. */
  5462. Matrix.prototype.setRow = function (index, row) {
  5463. if (index < 0 || index > 3) {
  5464. return this;
  5465. }
  5466. var i = index * 4;
  5467. this.m[i + 0] = row.x;
  5468. this.m[i + 1] = row.y;
  5469. this.m[i + 2] = row.z;
  5470. this.m[i + 3] = row.w;
  5471. this._markAsUpdated();
  5472. return this;
  5473. };
  5474. /**
  5475. * Compute the transpose of the matrix
  5476. * @returns the new transposed matrix
  5477. */
  5478. Matrix.prototype.transpose = function () {
  5479. return Matrix.Transpose(this);
  5480. };
  5481. /**
  5482. * Compute the transpose of the matrix and store it in a given matrix
  5483. * @param result defines the target matrix
  5484. * @returns the current matrix
  5485. */
  5486. Matrix.prototype.transposeToRef = function (result) {
  5487. Matrix.TransposeToRef(this, result);
  5488. return this;
  5489. };
  5490. /**
  5491. * Sets the index-th row of the current matrix with the given 4 x float values
  5492. * @param index defines the row index
  5493. * @param x defines the x component to set
  5494. * @param y defines the y component to set
  5495. * @param z defines the z component to set
  5496. * @param w defines the w component to set
  5497. * @returns the updated current matrix
  5498. */
  5499. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5500. if (index < 0 || index > 3) {
  5501. return this;
  5502. }
  5503. var i = index * 4;
  5504. this.m[i + 0] = x;
  5505. this.m[i + 1] = y;
  5506. this.m[i + 2] = z;
  5507. this.m[i + 3] = w;
  5508. this._markAsUpdated();
  5509. return this;
  5510. };
  5511. /**
  5512. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5513. * @param scale defines the scale factor
  5514. * @returns a new matrix
  5515. */
  5516. Matrix.prototype.scale = function (scale) {
  5517. var result = new Matrix();
  5518. this.scaleToRef(scale, result);
  5519. return result;
  5520. };
  5521. /**
  5522. * Scale the current matrix values by a factor to a given result matrix
  5523. * @param scale defines the scale factor
  5524. * @param result defines the matrix to store the result
  5525. * @returns the current matrix
  5526. */
  5527. Matrix.prototype.scaleToRef = function (scale, result) {
  5528. for (var index = 0; index < 16; index++) {
  5529. result.m[index] = this.m[index] * scale;
  5530. }
  5531. result._markAsUpdated();
  5532. return this;
  5533. };
  5534. /**
  5535. * Scale the current matrix values by a factor and add the result to a given matrix
  5536. * @param scale defines the scale factor
  5537. * @param result defines the Matrix to store the result
  5538. * @returns the current matrix
  5539. */
  5540. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5541. for (var index = 0; index < 16; index++) {
  5542. result.m[index] += this.m[index] * scale;
  5543. }
  5544. result._markAsUpdated();
  5545. return this;
  5546. };
  5547. /**
  5548. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5549. * @param ref matrix to store the result
  5550. */
  5551. Matrix.prototype.toNormalMatrix = function (ref) {
  5552. this.invertToRef(ref);
  5553. ref.transpose();
  5554. var m = ref.m;
  5555. 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);
  5556. };
  5557. /**
  5558. * Gets only rotation part of the current matrix
  5559. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5560. */
  5561. Matrix.prototype.getRotationMatrix = function () {
  5562. var result = Matrix.Identity();
  5563. this.getRotationMatrixToRef(result);
  5564. return result;
  5565. };
  5566. /**
  5567. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5568. * @param result defines the target matrix to store data to
  5569. * @returns the current matrix
  5570. */
  5571. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5572. var m = this.m;
  5573. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5574. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5575. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5576. if (this.determinant() <= 0) {
  5577. sy *= -1;
  5578. }
  5579. if (sx === 0 || sy === 0 || sz === 0) {
  5580. Matrix.IdentityToRef(result);
  5581. }
  5582. else {
  5583. 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);
  5584. }
  5585. return this;
  5586. };
  5587. // Statics
  5588. /**
  5589. * Creates a matrix from an array
  5590. * @param array defines the source array
  5591. * @param offset defines an offset in the source array
  5592. * @returns a new Matrix set from the starting index of the given array
  5593. */
  5594. Matrix.FromArray = function (array, offset) {
  5595. var result = new Matrix();
  5596. if (!offset) {
  5597. offset = 0;
  5598. }
  5599. Matrix.FromArrayToRef(array, offset, result);
  5600. return result;
  5601. };
  5602. /**
  5603. * Copy the content of an array into a given matrix
  5604. * @param array defines the source array
  5605. * @param offset defines an offset in the source array
  5606. * @param result defines the target matrix
  5607. */
  5608. Matrix.FromArrayToRef = function (array, offset, result) {
  5609. for (var index = 0; index < 16; index++) {
  5610. result.m[index] = array[index + offset];
  5611. }
  5612. result._markAsUpdated();
  5613. };
  5614. /**
  5615. * Stores an array into a matrix after having multiplied each component by a given factor
  5616. * @param array defines the source array
  5617. * @param offset defines the offset in the source array
  5618. * @param scale defines the scaling factor
  5619. * @param result defines the target matrix
  5620. */
  5621. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] = array[index + offset] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. };
  5627. /**
  5628. * Stores a list of values (16) inside a given matrix
  5629. * @param initialM11 defines 1st value of 1st row
  5630. * @param initialM12 defines 2nd value of 1st row
  5631. * @param initialM13 defines 3rd value of 1st row
  5632. * @param initialM14 defines 4th value of 1st row
  5633. * @param initialM21 defines 1st value of 2nd row
  5634. * @param initialM22 defines 2nd value of 2nd row
  5635. * @param initialM23 defines 3rd value of 2nd row
  5636. * @param initialM24 defines 4th value of 2nd row
  5637. * @param initialM31 defines 1st value of 3rd row
  5638. * @param initialM32 defines 2nd value of 3rd row
  5639. * @param initialM33 defines 3rd value of 3rd row
  5640. * @param initialM34 defines 4th value of 3rd row
  5641. * @param initialM41 defines 1st value of 4th row
  5642. * @param initialM42 defines 2nd value of 4th row
  5643. * @param initialM43 defines 3rd value of 4th row
  5644. * @param initialM44 defines 4th value of 4th row
  5645. * @param result defines the target matrix
  5646. */
  5647. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5648. result.m[0] = initialM11;
  5649. result.m[1] = initialM12;
  5650. result.m[2] = initialM13;
  5651. result.m[3] = initialM14;
  5652. result.m[4] = initialM21;
  5653. result.m[5] = initialM22;
  5654. result.m[6] = initialM23;
  5655. result.m[7] = initialM24;
  5656. result.m[8] = initialM31;
  5657. result.m[9] = initialM32;
  5658. result.m[10] = initialM33;
  5659. result.m[11] = initialM34;
  5660. result.m[12] = initialM41;
  5661. result.m[13] = initialM42;
  5662. result.m[14] = initialM43;
  5663. result.m[15] = initialM44;
  5664. result._markAsUpdated();
  5665. };
  5666. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5667. /**
  5668. * Gets an identity matrix that must not be updated
  5669. */
  5670. get: function () {
  5671. return Matrix._identityReadOnly;
  5672. },
  5673. enumerable: true,
  5674. configurable: true
  5675. });
  5676. /**
  5677. * Creates new matrix from a list of values (16)
  5678. * @param initialM11 defines 1st value of 1st row
  5679. * @param initialM12 defines 2nd value of 1st row
  5680. * @param initialM13 defines 3rd value of 1st row
  5681. * @param initialM14 defines 4th value of 1st row
  5682. * @param initialM21 defines 1st value of 2nd row
  5683. * @param initialM22 defines 2nd value of 2nd row
  5684. * @param initialM23 defines 3rd value of 2nd row
  5685. * @param initialM24 defines 4th value of 2nd row
  5686. * @param initialM31 defines 1st value of 3rd row
  5687. * @param initialM32 defines 2nd value of 3rd row
  5688. * @param initialM33 defines 3rd value of 3rd row
  5689. * @param initialM34 defines 4th value of 3rd row
  5690. * @param initialM41 defines 1st value of 4th row
  5691. * @param initialM42 defines 2nd value of 4th row
  5692. * @param initialM43 defines 3rd value of 4th row
  5693. * @param initialM44 defines 4th value of 4th row
  5694. * @returns the new matrix
  5695. */
  5696. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5697. var result = new Matrix();
  5698. result.m[0] = initialM11;
  5699. result.m[1] = initialM12;
  5700. result.m[2] = initialM13;
  5701. result.m[3] = initialM14;
  5702. result.m[4] = initialM21;
  5703. result.m[5] = initialM22;
  5704. result.m[6] = initialM23;
  5705. result.m[7] = initialM24;
  5706. result.m[8] = initialM31;
  5707. result.m[9] = initialM32;
  5708. result.m[10] = initialM33;
  5709. result.m[11] = initialM34;
  5710. result.m[12] = initialM41;
  5711. result.m[13] = initialM42;
  5712. result.m[14] = initialM43;
  5713. result.m[15] = initialM44;
  5714. return result;
  5715. };
  5716. /**
  5717. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5718. * @param scale defines the scale vector3
  5719. * @param rotation defines the rotation quaternion
  5720. * @param translation defines the translation vector3
  5721. * @returns a new matrix
  5722. */
  5723. Matrix.Compose = function (scale, rotation, translation) {
  5724. var result = Matrix.Identity();
  5725. Matrix.ComposeToRef(scale, rotation, translation, result);
  5726. return result;
  5727. };
  5728. /**
  5729. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5730. * @param scale defines the scale vector3
  5731. * @param rotation defines the rotation quaternion
  5732. * @param translation defines the translation vector3
  5733. * @param result defines the target matrix
  5734. */
  5735. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5736. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5737. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5738. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5739. result.setTranslation(translation);
  5740. };
  5741. /**
  5742. * Creates a new identity matrix
  5743. * @returns a new identity matrix
  5744. */
  5745. Matrix.Identity = function () {
  5746. 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);
  5747. };
  5748. /**
  5749. * Creates a new identity matrix and stores the result in a given matrix
  5750. * @param result defines the target matrix
  5751. */
  5752. Matrix.IdentityToRef = function (result) {
  5753. 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);
  5754. };
  5755. /**
  5756. * Creates a new zero matrix
  5757. * @returns a new zero matrix
  5758. */
  5759. Matrix.Zero = function () {
  5760. 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);
  5761. };
  5762. /**
  5763. * Creates a new rotation matrix for "angle" radians around the X axis
  5764. * @param angle defines the angle (in radians) to use
  5765. * @return the new matrix
  5766. */
  5767. Matrix.RotationX = function (angle) {
  5768. var result = new Matrix();
  5769. Matrix.RotationXToRef(angle, result);
  5770. return result;
  5771. };
  5772. /**
  5773. * Creates a new matrix as the invert of a given matrix
  5774. * @param source defines the source matrix
  5775. * @returns the new matrix
  5776. */
  5777. Matrix.Invert = function (source) {
  5778. var result = new Matrix();
  5779. source.invertToRef(result);
  5780. return result;
  5781. };
  5782. /**
  5783. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5784. * @param angle defines the angle (in radians) to use
  5785. * @param result defines the target matrix
  5786. */
  5787. Matrix.RotationXToRef = function (angle, result) {
  5788. var s = Math.sin(angle);
  5789. var c = Math.cos(angle);
  5790. result.m[0] = 1.0;
  5791. result.m[15] = 1.0;
  5792. result.m[5] = c;
  5793. result.m[10] = c;
  5794. result.m[9] = -s;
  5795. result.m[6] = s;
  5796. result.m[1] = 0.0;
  5797. result.m[2] = 0.0;
  5798. result.m[3] = 0.0;
  5799. result.m[4] = 0.0;
  5800. result.m[7] = 0.0;
  5801. result.m[8] = 0.0;
  5802. result.m[11] = 0.0;
  5803. result.m[12] = 0.0;
  5804. result.m[13] = 0.0;
  5805. result.m[14] = 0.0;
  5806. result._markAsUpdated();
  5807. };
  5808. /**
  5809. * Creates a new rotation matrix for "angle" radians around the Y axis
  5810. * @param angle defines the angle (in radians) to use
  5811. * @return the new matrix
  5812. */
  5813. Matrix.RotationY = function (angle) {
  5814. var result = new Matrix();
  5815. Matrix.RotationYToRef(angle, result);
  5816. return result;
  5817. };
  5818. /**
  5819. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5820. * @param angle defines the angle (in radians) to use
  5821. * @param result defines the target matrix
  5822. */
  5823. Matrix.RotationYToRef = function (angle, result) {
  5824. var s = Math.sin(angle);
  5825. var c = Math.cos(angle);
  5826. result.m[5] = 1.0;
  5827. result.m[15] = 1.0;
  5828. result.m[0] = c;
  5829. result.m[2] = -s;
  5830. result.m[8] = s;
  5831. result.m[10] = c;
  5832. result.m[1] = 0.0;
  5833. result.m[3] = 0.0;
  5834. result.m[4] = 0.0;
  5835. result.m[6] = 0.0;
  5836. result.m[7] = 0.0;
  5837. result.m[9] = 0.0;
  5838. result.m[11] = 0.0;
  5839. result.m[12] = 0.0;
  5840. result.m[13] = 0.0;
  5841. result.m[14] = 0.0;
  5842. result._markAsUpdated();
  5843. };
  5844. /**
  5845. * Creates a new rotation matrix for "angle" radians around the Z axis
  5846. * @param angle defines the angle (in radians) to use
  5847. * @return the new matrix
  5848. */
  5849. Matrix.RotationZ = function (angle) {
  5850. var result = new Matrix();
  5851. Matrix.RotationZToRef(angle, result);
  5852. return result;
  5853. };
  5854. /**
  5855. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5856. * @param angle defines the angle (in radians) to use
  5857. * @param result defines the target matrix
  5858. */
  5859. Matrix.RotationZToRef = function (angle, result) {
  5860. var s = Math.sin(angle);
  5861. var c = Math.cos(angle);
  5862. result.m[10] = 1.0;
  5863. result.m[15] = 1.0;
  5864. result.m[0] = c;
  5865. result.m[1] = s;
  5866. result.m[4] = -s;
  5867. result.m[5] = c;
  5868. result.m[2] = 0.0;
  5869. result.m[3] = 0.0;
  5870. result.m[6] = 0.0;
  5871. result.m[7] = 0.0;
  5872. result.m[8] = 0.0;
  5873. result.m[9] = 0.0;
  5874. result.m[11] = 0.0;
  5875. result.m[12] = 0.0;
  5876. result.m[13] = 0.0;
  5877. result.m[14] = 0.0;
  5878. result._markAsUpdated();
  5879. };
  5880. /**
  5881. * Creates a new rotation matrix for "angle" radians around the given axis
  5882. * @param axis defines the axis to use
  5883. * @param angle defines the angle (in radians) to use
  5884. * @return the new matrix
  5885. */
  5886. Matrix.RotationAxis = function (axis, angle) {
  5887. var result = Matrix.Zero();
  5888. Matrix.RotationAxisToRef(axis, angle, result);
  5889. return result;
  5890. };
  5891. /**
  5892. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5893. * @param axis defines the axis to use
  5894. * @param angle defines the angle (in radians) to use
  5895. * @param result defines the target matrix
  5896. */
  5897. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5898. var s = Math.sin(-angle);
  5899. var c = Math.cos(-angle);
  5900. var c1 = 1 - c;
  5901. axis.normalize();
  5902. result.m[0] = (axis.x * axis.x) * c1 + c;
  5903. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5904. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5905. result.m[3] = 0.0;
  5906. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5907. result.m[5] = (axis.y * axis.y) * c1 + c;
  5908. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5909. result.m[7] = 0.0;
  5910. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5911. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5912. result.m[10] = (axis.z * axis.z) * c1 + c;
  5913. result.m[11] = 0.0;
  5914. result.m[15] = 1.0;
  5915. result._markAsUpdated();
  5916. };
  5917. /**
  5918. * Creates a rotation matrix
  5919. * @param yaw defines the yaw angle in radians (Y axis)
  5920. * @param pitch defines the pitch angle in radians (X axis)
  5921. * @param roll defines the roll angle in radians (X axis)
  5922. * @returns the new rotation matrix
  5923. */
  5924. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5925. var result = new Matrix();
  5926. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5927. return result;
  5928. };
  5929. /**
  5930. * Creates a rotation matrix and stores it in a given matrix
  5931. * @param yaw defines the yaw angle in radians (Y axis)
  5932. * @param pitch defines the pitch angle in radians (X axis)
  5933. * @param roll defines the roll angle in radians (X axis)
  5934. * @param result defines the target matrix
  5935. */
  5936. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5937. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5938. this._tempQuaternion.toRotationMatrix(result);
  5939. };
  5940. /**
  5941. * Creates a scaling matrix
  5942. * @param x defines the scale factor on X axis
  5943. * @param y defines the scale factor on Y axis
  5944. * @param z defines the scale factor on Z axis
  5945. * @returns the new matrix
  5946. */
  5947. Matrix.Scaling = function (x, y, z) {
  5948. var result = Matrix.Zero();
  5949. Matrix.ScalingToRef(x, y, z, result);
  5950. return result;
  5951. };
  5952. /**
  5953. * Creates a scaling matrix and stores it in a given matrix
  5954. * @param x defines the scale factor on X axis
  5955. * @param y defines the scale factor on Y axis
  5956. * @param z defines the scale factor on Z axis
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.ScalingToRef = function (x, y, z, result) {
  5960. result.m[0] = x;
  5961. result.m[1] = 0.0;
  5962. result.m[2] = 0.0;
  5963. result.m[3] = 0.0;
  5964. result.m[4] = 0.0;
  5965. result.m[5] = y;
  5966. result.m[6] = 0.0;
  5967. result.m[7] = 0.0;
  5968. result.m[8] = 0.0;
  5969. result.m[9] = 0.0;
  5970. result.m[10] = z;
  5971. result.m[11] = 0.0;
  5972. result.m[12] = 0.0;
  5973. result.m[13] = 0.0;
  5974. result.m[14] = 0.0;
  5975. result.m[15] = 1.0;
  5976. result._markAsUpdated();
  5977. };
  5978. /**
  5979. * Creates a translation matrix
  5980. * @param x defines the translation on X axis
  5981. * @param y defines the translation on Y axis
  5982. * @param z defines the translationon Z axis
  5983. * @returns the new matrix
  5984. */
  5985. Matrix.Translation = function (x, y, z) {
  5986. var result = Matrix.Identity();
  5987. Matrix.TranslationToRef(x, y, z, result);
  5988. return result;
  5989. };
  5990. /**
  5991. * Creates a translation matrix and stores it in a given matrix
  5992. * @param x defines the translation on X axis
  5993. * @param y defines the translation on Y axis
  5994. * @param z defines the translationon Z axis
  5995. * @param result defines the target matrix
  5996. */
  5997. Matrix.TranslationToRef = function (x, y, z, result) {
  5998. 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);
  5999. };
  6000. /**
  6001. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6002. * @param startValue defines the start value
  6003. * @param endValue defines the end value
  6004. * @param gradient defines the gradient factor
  6005. * @returns the new matrix
  6006. */
  6007. Matrix.Lerp = function (startValue, endValue, gradient) {
  6008. var result = Matrix.Zero();
  6009. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6010. return result;
  6011. };
  6012. /**
  6013. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6014. * @param startValue defines the start value
  6015. * @param endValue defines the end value
  6016. * @param gradient defines the gradient factor
  6017. * @param result defines the Matrix object where to store data
  6018. */
  6019. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6020. for (var index = 0; index < 16; index++) {
  6021. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6022. }
  6023. result._markAsUpdated();
  6024. };
  6025. /**
  6026. * Builds a new matrix whose values are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @returns the new matrix
  6034. */
  6035. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6036. var result = Matrix.Zero();
  6037. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6038. return result;
  6039. };
  6040. /**
  6041. * Update a matrix to values which are computed by:
  6042. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6043. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6044. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6045. * @param startValue defines the first matrix
  6046. * @param endValue defines the second matrix
  6047. * @param gradient defines the gradient between the two matrices
  6048. * @param result defines the target matrix
  6049. */
  6050. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6051. var startScale = MathTmp.Vector3[0];
  6052. var startRotation = MathTmp.Quaternion[0];
  6053. var startTranslation = MathTmp.Vector3[1];
  6054. startValue.decompose(startScale, startRotation, startTranslation);
  6055. var endScale = MathTmp.Vector3[2];
  6056. var endRotation = MathTmp.Quaternion[1];
  6057. var endTranslation = MathTmp.Vector3[3];
  6058. endValue.decompose(endScale, endRotation, endTranslation);
  6059. var resultScale = MathTmp.Vector3[4];
  6060. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6061. var resultRotation = MathTmp.Quaternion[2];
  6062. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6063. var resultTranslation = MathTmp.Vector3[5];
  6064. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6065. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6066. };
  6067. /**
  6068. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6069. * This function works in left handed mode
  6070. * @param eye defines the final position of the entity
  6071. * @param target defines where the entity should look at
  6072. * @param up defines the up vector for the entity
  6073. * @returns the new matrix
  6074. */
  6075. Matrix.LookAtLH = function (eye, target, up) {
  6076. var result = Matrix.Zero();
  6077. Matrix.LookAtLHToRef(eye, target, up, result);
  6078. return result;
  6079. };
  6080. /**
  6081. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6082. * This function works in left handed mode
  6083. * @param eye defines the final position of the entity
  6084. * @param target defines where the entity should look at
  6085. * @param up defines the up vector for the entity
  6086. * @param result defines the target matrix
  6087. */
  6088. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6089. // Z axis
  6090. target.subtractToRef(eye, this._zAxis);
  6091. this._zAxis.normalize();
  6092. // X axis
  6093. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6094. if (this._xAxis.lengthSquared() === 0) {
  6095. this._xAxis.x = 1.0;
  6096. }
  6097. else {
  6098. this._xAxis.normalize();
  6099. }
  6100. // Y axis
  6101. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6102. this._yAxis.normalize();
  6103. // Eye angles
  6104. var ex = -Vector3.Dot(this._xAxis, eye);
  6105. var ey = -Vector3.Dot(this._yAxis, eye);
  6106. var ez = -Vector3.Dot(this._zAxis, eye);
  6107. 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);
  6108. };
  6109. /**
  6110. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6111. * This function works in right handed mode
  6112. * @param eye defines the final position of the entity
  6113. * @param target defines where the entity should look at
  6114. * @param up defines the up vector for the entity
  6115. * @returns the new matrix
  6116. */
  6117. Matrix.LookAtRH = function (eye, target, up) {
  6118. var result = Matrix.Zero();
  6119. Matrix.LookAtRHToRef(eye, target, up, result);
  6120. return result;
  6121. };
  6122. /**
  6123. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6124. * This function works in right handed mode
  6125. * @param eye defines the final position of the entity
  6126. * @param target defines where the entity should look at
  6127. * @param up defines the up vector for the entity
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6131. // Z axis
  6132. eye.subtractToRef(target, this._zAxis);
  6133. this._zAxis.normalize();
  6134. // X axis
  6135. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6136. if (this._xAxis.lengthSquared() === 0) {
  6137. this._xAxis.x = 1.0;
  6138. }
  6139. else {
  6140. this._xAxis.normalize();
  6141. }
  6142. // Y axis
  6143. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6144. this._yAxis.normalize();
  6145. // Eye angles
  6146. var ex = -Vector3.Dot(this._xAxis, eye);
  6147. var ey = -Vector3.Dot(this._yAxis, eye);
  6148. var ez = -Vector3.Dot(this._zAxis, eye);
  6149. 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);
  6150. };
  6151. /**
  6152. * Create a left-handed orthographic projection matrix
  6153. * @param width defines the viewport width
  6154. * @param height defines the viewport height
  6155. * @param znear defines the near clip plane
  6156. * @param zfar defines the far clip plane
  6157. * @returns a new matrix as a left-handed orthographic projection matrix
  6158. */
  6159. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6160. var matrix = Matrix.Zero();
  6161. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6162. return matrix;
  6163. };
  6164. /**
  6165. * Store a left-handed orthographic projection to a given matrix
  6166. * @param width defines the viewport width
  6167. * @param height defines the viewport height
  6168. * @param znear defines the near clip plane
  6169. * @param zfar defines the far clip plane
  6170. * @param result defines the target matrix
  6171. */
  6172. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6173. var n = znear;
  6174. var f = zfar;
  6175. var a = 2.0 / width;
  6176. var b = 2.0 / height;
  6177. var c = 2.0 / (f - n);
  6178. var d = -(f + n) / (f - n);
  6179. 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);
  6180. };
  6181. /**
  6182. * Create a left-handed orthographic projection matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @returns a new matrix as a left-handed orthographic projection matrix
  6190. */
  6191. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6192. var matrix = Matrix.Zero();
  6193. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6194. return matrix;
  6195. };
  6196. /**
  6197. * Stores a left-handed orthographic projection into a given matrix
  6198. * @param left defines the viewport left coordinate
  6199. * @param right defines the viewport right coordinate
  6200. * @param bottom defines the viewport bottom coordinate
  6201. * @param top defines the viewport top coordinate
  6202. * @param znear defines the near clip plane
  6203. * @param zfar defines the far clip plane
  6204. * @param result defines the target matrix
  6205. */
  6206. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6207. var n = znear;
  6208. var f = zfar;
  6209. var a = 2.0 / (right - left);
  6210. var b = 2.0 / (top - bottom);
  6211. var c = 2.0 / (f - n);
  6212. var d = -(f + n) / (f - n);
  6213. var i0 = (left + right) / (left - right);
  6214. var i1 = (top + bottom) / (bottom - top);
  6215. 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);
  6216. };
  6217. /**
  6218. * Creates a right-handed orthographic projection matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a right-handed orthographic projection matrix
  6226. */
  6227. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6230. return matrix;
  6231. };
  6232. /**
  6233. * Stores a right-handed orthographic projection into a given matrix
  6234. * @param left defines the viewport left coordinate
  6235. * @param right defines the viewport right coordinate
  6236. * @param bottom defines the viewport bottom coordinate
  6237. * @param top defines the viewport top coordinate
  6238. * @param znear defines the near clip plane
  6239. * @param zfar defines the far clip plane
  6240. * @param result defines the target matrix
  6241. */
  6242. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6243. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6244. result.m[10] *= -1.0;
  6245. };
  6246. /**
  6247. * Creates a left-handed perspective projection matrix
  6248. * @param width defines the viewport width
  6249. * @param height defines the viewport height
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @returns a new matrix as a left-handed perspective projection matrix
  6253. */
  6254. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6255. var matrix = Matrix.Zero();
  6256. var n = znear;
  6257. var f = zfar;
  6258. var a = 2.0 * n / width;
  6259. var b = 2.0 * n / height;
  6260. var c = (f + n) / (f - n);
  6261. var d = -2.0 * f * n / (f - n);
  6262. 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);
  6263. return matrix;
  6264. };
  6265. /**
  6266. * Creates a left-handed perspective projection matrix
  6267. * @param fov defines the horizontal field of view
  6268. * @param aspect defines the aspect ratio
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @returns a new matrix as a left-handed perspective projection matrix
  6272. */
  6273. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6274. var matrix = Matrix.Zero();
  6275. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6276. return matrix;
  6277. };
  6278. /**
  6279. * Stores a left-handed perspective projection into a given matrix
  6280. * @param fov defines the horizontal field of view
  6281. * @param aspect defines the aspect ratio
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6286. */
  6287. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6288. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6289. var n = znear;
  6290. var f = zfar;
  6291. var t = 1.0 / (Math.tan(fov * 0.5));
  6292. var a = isVerticalFovFixed ? (t / aspect) : t;
  6293. var b = isVerticalFovFixed ? t : (t * aspect);
  6294. var c = (f + n) / (f - n);
  6295. var d = -2.0 * f * n / (f - n);
  6296. 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);
  6297. };
  6298. /**
  6299. * Creates a right-handed perspective projection matrix
  6300. * @param fov defines the horizontal field of view
  6301. * @param aspect defines the aspect ratio
  6302. * @param znear defines the near clip plane
  6303. * @param zfar defines the far clip plane
  6304. * @returns a new matrix as a right-handed perspective projection matrix
  6305. */
  6306. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6307. var matrix = Matrix.Zero();
  6308. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6309. return matrix;
  6310. };
  6311. /**
  6312. * Stores a right-handed perspective projection into a given matrix
  6313. * @param fov defines the horizontal field of view
  6314. * @param aspect defines the aspect ratio
  6315. * @param znear defines the near clip plane
  6316. * @param zfar defines the far clip plane
  6317. * @param result defines the target matrix
  6318. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6319. */
  6320. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6321. //alternatively this could be expressed as:
  6322. // m = PerspectiveFovLHToRef
  6323. // m[10] *= -1.0;
  6324. // m[11] *= -1.0;
  6325. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6326. var n = znear;
  6327. var f = zfar;
  6328. var t = 1.0 / (Math.tan(fov * 0.5));
  6329. var a = isVerticalFovFixed ? (t / aspect) : t;
  6330. var b = isVerticalFovFixed ? t : (t * aspect);
  6331. var c = -(f + n) / (f - n);
  6332. var d = -2 * f * n / (f - n);
  6333. 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);
  6334. };
  6335. /**
  6336. * Stores a perspective projection for WebVR info a given matrix
  6337. * @param fov defines the field of view
  6338. * @param znear defines the near clip plane
  6339. * @param zfar defines the far clip plane
  6340. * @param result defines the target matrix
  6341. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6342. */
  6343. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6344. if (rightHanded === void 0) { rightHanded = false; }
  6345. var rightHandedFactor = rightHanded ? -1 : 1;
  6346. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6347. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6348. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6349. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6350. var xScale = 2.0 / (leftTan + rightTan);
  6351. var yScale = 2.0 / (upTan + downTan);
  6352. result.m[0] = xScale;
  6353. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6354. result.m[5] = yScale;
  6355. result.m[6] = result.m[7] = 0.0;
  6356. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6357. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6358. result.m[10] = -zfar / (znear - zfar);
  6359. result.m[11] = 1.0 * rightHandedFactor;
  6360. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6361. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6362. result._markAsUpdated();
  6363. };
  6364. /**
  6365. * Computes a complete transformation matrix
  6366. * @param viewport defines the viewport to use
  6367. * @param world defines the world matrix
  6368. * @param view defines the view matrix
  6369. * @param projection defines the projection matrix
  6370. * @param zmin defines the near clip plane
  6371. * @param zmax defines the far clip plane
  6372. * @returns the transformation matrix
  6373. */
  6374. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6375. var cw = viewport.width;
  6376. var ch = viewport.height;
  6377. var cx = viewport.x;
  6378. var cy = viewport.y;
  6379. 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);
  6380. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6381. };
  6382. /**
  6383. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6384. * @param matrix defines the matrix to use
  6385. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6386. */
  6387. Matrix.GetAsMatrix2x2 = function (matrix) {
  6388. return new Float32Array([
  6389. matrix.m[0], matrix.m[1],
  6390. matrix.m[4], matrix.m[5]
  6391. ]);
  6392. };
  6393. /**
  6394. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6395. * @param matrix defines the matrix to use
  6396. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6397. */
  6398. Matrix.GetAsMatrix3x3 = function (matrix) {
  6399. return new Float32Array([
  6400. matrix.m[0], matrix.m[1], matrix.m[2],
  6401. matrix.m[4], matrix.m[5], matrix.m[6],
  6402. matrix.m[8], matrix.m[9], matrix.m[10]
  6403. ]);
  6404. };
  6405. /**
  6406. * Compute the transpose of a given matrix
  6407. * @param matrix defines the matrix to transpose
  6408. * @returns the new matrix
  6409. */
  6410. Matrix.Transpose = function (matrix) {
  6411. var result = new Matrix();
  6412. Matrix.TransposeToRef(matrix, result);
  6413. return result;
  6414. };
  6415. /**
  6416. * Compute the transpose of a matrix and store it in a target matrix
  6417. * @param matrix defines the matrix to transpose
  6418. * @param result defines the target matrix
  6419. */
  6420. Matrix.TransposeToRef = function (matrix, result) {
  6421. result.m[0] = matrix.m[0];
  6422. result.m[1] = matrix.m[4];
  6423. result.m[2] = matrix.m[8];
  6424. result.m[3] = matrix.m[12];
  6425. result.m[4] = matrix.m[1];
  6426. result.m[5] = matrix.m[5];
  6427. result.m[6] = matrix.m[9];
  6428. result.m[7] = matrix.m[13];
  6429. result.m[8] = matrix.m[2];
  6430. result.m[9] = matrix.m[6];
  6431. result.m[10] = matrix.m[10];
  6432. result.m[11] = matrix.m[14];
  6433. result.m[12] = matrix.m[3];
  6434. result.m[13] = matrix.m[7];
  6435. result.m[14] = matrix.m[11];
  6436. result.m[15] = matrix.m[15];
  6437. };
  6438. /**
  6439. * Computes a reflection matrix from a plane
  6440. * @param plane defines the reflection plane
  6441. * @returns a new matrix
  6442. */
  6443. Matrix.Reflection = function (plane) {
  6444. var matrix = new Matrix();
  6445. Matrix.ReflectionToRef(plane, matrix);
  6446. return matrix;
  6447. };
  6448. /**
  6449. * Computes a reflection matrix from a plane
  6450. * @param plane defines the reflection plane
  6451. * @param result defines the target matrix
  6452. */
  6453. Matrix.ReflectionToRef = function (plane, result) {
  6454. plane.normalize();
  6455. var x = plane.normal.x;
  6456. var y = plane.normal.y;
  6457. var z = plane.normal.z;
  6458. var temp = -2 * x;
  6459. var temp2 = -2 * y;
  6460. var temp3 = -2 * z;
  6461. result.m[0] = (temp * x) + 1;
  6462. result.m[1] = temp2 * x;
  6463. result.m[2] = temp3 * x;
  6464. result.m[3] = 0.0;
  6465. result.m[4] = temp * y;
  6466. result.m[5] = (temp2 * y) + 1;
  6467. result.m[6] = temp3 * y;
  6468. result.m[7] = 0.0;
  6469. result.m[8] = temp * z;
  6470. result.m[9] = temp2 * z;
  6471. result.m[10] = (temp3 * z) + 1;
  6472. result.m[11] = 0.0;
  6473. result.m[12] = temp * plane.d;
  6474. result.m[13] = temp2 * plane.d;
  6475. result.m[14] = temp3 * plane.d;
  6476. result.m[15] = 1.0;
  6477. result._markAsUpdated();
  6478. };
  6479. /**
  6480. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6481. * @param xaxis defines the value of the 1st axis
  6482. * @param yaxis defines the value of the 2nd axis
  6483. * @param zaxis defines the value of the 3rd axis
  6484. * @param result defines the target matrix
  6485. */
  6486. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6487. result.m[0] = xaxis.x;
  6488. result.m[1] = xaxis.y;
  6489. result.m[2] = xaxis.z;
  6490. result.m[3] = 0.0;
  6491. result.m[4] = yaxis.x;
  6492. result.m[5] = yaxis.y;
  6493. result.m[6] = yaxis.z;
  6494. result.m[7] = 0.0;
  6495. result.m[8] = zaxis.x;
  6496. result.m[9] = zaxis.y;
  6497. result.m[10] = zaxis.z;
  6498. result.m[11] = 0.0;
  6499. result.m[12] = 0.0;
  6500. result.m[13] = 0.0;
  6501. result.m[14] = 0.0;
  6502. result.m[15] = 1.0;
  6503. result._markAsUpdated();
  6504. };
  6505. /**
  6506. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6507. * @param quat defines the quaternion to use
  6508. * @param result defines the target matrix
  6509. */
  6510. Matrix.FromQuaternionToRef = function (quat, result) {
  6511. var xx = quat.x * quat.x;
  6512. var yy = quat.y * quat.y;
  6513. var zz = quat.z * quat.z;
  6514. var xy = quat.x * quat.y;
  6515. var zw = quat.z * quat.w;
  6516. var zx = quat.z * quat.x;
  6517. var yw = quat.y * quat.w;
  6518. var yz = quat.y * quat.z;
  6519. var xw = quat.x * quat.w;
  6520. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6521. result.m[1] = 2.0 * (xy + zw);
  6522. result.m[2] = 2.0 * (zx - yw);
  6523. result.m[3] = 0.0;
  6524. result.m[4] = 2.0 * (xy - zw);
  6525. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6526. result.m[6] = 2.0 * (yz + xw);
  6527. result.m[7] = 0.0;
  6528. result.m[8] = 2.0 * (zx + yw);
  6529. result.m[9] = 2.0 * (yz - xw);
  6530. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6531. result.m[11] = 0.0;
  6532. result.m[12] = 0.0;
  6533. result.m[13] = 0.0;
  6534. result.m[14] = 0.0;
  6535. result.m[15] = 1.0;
  6536. result._markAsUpdated();
  6537. };
  6538. Matrix._tempQuaternion = new Quaternion();
  6539. Matrix._xAxis = Vector3.Zero();
  6540. Matrix._yAxis = Vector3.Zero();
  6541. Matrix._zAxis = Vector3.Zero();
  6542. Matrix._updateFlagSeed = 0;
  6543. Matrix._identityReadOnly = Matrix.Identity();
  6544. return Matrix;
  6545. }());
  6546. BABYLON.Matrix = Matrix;
  6547. var Plane = /** @class */ (function () {
  6548. /**
  6549. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6550. */
  6551. function Plane(a, b, c, d) {
  6552. this.normal = new Vector3(a, b, c);
  6553. this.d = d;
  6554. }
  6555. /**
  6556. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6557. */
  6558. Plane.prototype.asArray = function () {
  6559. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6560. };
  6561. // Methods
  6562. /**
  6563. * Returns a new plane copied from the current Plane.
  6564. */
  6565. Plane.prototype.clone = function () {
  6566. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6567. };
  6568. /**
  6569. * Returns the string "Plane".
  6570. */
  6571. Plane.prototype.getClassName = function () {
  6572. return "Plane";
  6573. };
  6574. /**
  6575. * Returns the Plane hash code.
  6576. */
  6577. Plane.prototype.getHashCode = function () {
  6578. var hash = this.normal.getHashCode();
  6579. hash = (hash * 397) ^ (this.d || 0);
  6580. return hash;
  6581. };
  6582. /**
  6583. * Normalize the current Plane in place.
  6584. * Returns the updated Plane.
  6585. */
  6586. Plane.prototype.normalize = function () {
  6587. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6588. var magnitude = 0.0;
  6589. if (norm !== 0) {
  6590. magnitude = 1.0 / norm;
  6591. }
  6592. this.normal.x *= magnitude;
  6593. this.normal.y *= magnitude;
  6594. this.normal.z *= magnitude;
  6595. this.d *= magnitude;
  6596. return this;
  6597. };
  6598. /**
  6599. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6600. */
  6601. Plane.prototype.transform = function (transformation) {
  6602. var transposedMatrix = Matrix.Transpose(transformation);
  6603. var x = this.normal.x;
  6604. var y = this.normal.y;
  6605. var z = this.normal.z;
  6606. var d = this.d;
  6607. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6608. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6609. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6610. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6611. return new Plane(normalX, normalY, normalZ, finalD);
  6612. };
  6613. /**
  6614. * Returns the dot product (float) of the point coordinates and the plane normal.
  6615. */
  6616. Plane.prototype.dotCoordinate = function (point) {
  6617. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6618. };
  6619. /**
  6620. * Updates the current Plane from the plane defined by the three given points.
  6621. * Returns the updated Plane.
  6622. */
  6623. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6624. var x1 = point2.x - point1.x;
  6625. var y1 = point2.y - point1.y;
  6626. var z1 = point2.z - point1.z;
  6627. var x2 = point3.x - point1.x;
  6628. var y2 = point3.y - point1.y;
  6629. var z2 = point3.z - point1.z;
  6630. var yz = (y1 * z2) - (z1 * y2);
  6631. var xz = (z1 * x2) - (x1 * z2);
  6632. var xy = (x1 * y2) - (y1 * x2);
  6633. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6634. var invPyth;
  6635. if (pyth !== 0) {
  6636. invPyth = 1.0 / pyth;
  6637. }
  6638. else {
  6639. invPyth = 0.0;
  6640. }
  6641. this.normal.x = yz * invPyth;
  6642. this.normal.y = xz * invPyth;
  6643. this.normal.z = xy * invPyth;
  6644. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6645. return this;
  6646. };
  6647. /**
  6648. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6649. */
  6650. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6651. var dot = Vector3.Dot(this.normal, direction);
  6652. return (dot <= epsilon);
  6653. };
  6654. /**
  6655. * Returns the signed distance (float) from the given point to the Plane.
  6656. */
  6657. Plane.prototype.signedDistanceTo = function (point) {
  6658. return Vector3.Dot(point, this.normal) + this.d;
  6659. };
  6660. // Statics
  6661. /**
  6662. * Returns a new Plane from the given array.
  6663. */
  6664. Plane.FromArray = function (array) {
  6665. return new Plane(array[0], array[1], array[2], array[3]);
  6666. };
  6667. /**
  6668. * Returns a new Plane defined by the three given points.
  6669. */
  6670. Plane.FromPoints = function (point1, point2, point3) {
  6671. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6672. result.copyFromPoints(point1, point2, point3);
  6673. return result;
  6674. };
  6675. /**
  6676. * Returns a new Plane the normal vector to this plane at the given origin point.
  6677. * Note : the vector "normal" is updated because normalized.
  6678. */
  6679. Plane.FromPositionAndNormal = function (origin, normal) {
  6680. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6681. normal.normalize();
  6682. result.normal = normal;
  6683. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6684. return result;
  6685. };
  6686. /**
  6687. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6688. */
  6689. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6690. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6691. return Vector3.Dot(point, normal) + d;
  6692. };
  6693. return Plane;
  6694. }());
  6695. BABYLON.Plane = Plane;
  6696. var Viewport = /** @class */ (function () {
  6697. /**
  6698. * Creates a Viewport object located at (x, y) and sized (width, height).
  6699. */
  6700. function Viewport(x, y, width, height) {
  6701. this.x = x;
  6702. this.y = y;
  6703. this.width = width;
  6704. this.height = height;
  6705. }
  6706. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6707. if (renderWidthOrEngine.getRenderWidth) {
  6708. var engine = renderWidthOrEngine;
  6709. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6710. }
  6711. var renderWidth = renderWidthOrEngine;
  6712. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6713. };
  6714. /**
  6715. * Returns a new Viewport copied from the current one.
  6716. */
  6717. Viewport.prototype.clone = function () {
  6718. return new Viewport(this.x, this.y, this.width, this.height);
  6719. };
  6720. return Viewport;
  6721. }());
  6722. BABYLON.Viewport = Viewport;
  6723. var Frustum = /** @class */ (function () {
  6724. function Frustum() {
  6725. }
  6726. /**
  6727. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6728. */
  6729. Frustum.GetPlanes = function (transform) {
  6730. var frustumPlanes = [];
  6731. for (var index = 0; index < 6; index++) {
  6732. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6733. }
  6734. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6735. return frustumPlanes;
  6736. };
  6737. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6738. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6739. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6740. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6741. frustumPlane.d = transform.m[15] + transform.m[14];
  6742. frustumPlane.normalize();
  6743. };
  6744. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6745. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6746. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6747. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6748. frustumPlane.d = transform.m[15] - transform.m[14];
  6749. frustumPlane.normalize();
  6750. };
  6751. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6752. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6753. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6754. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6755. frustumPlane.d = transform.m[15] + transform.m[12];
  6756. frustumPlane.normalize();
  6757. };
  6758. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6759. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6760. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6761. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6762. frustumPlane.d = transform.m[15] - transform.m[12];
  6763. frustumPlane.normalize();
  6764. };
  6765. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6766. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6767. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6768. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6769. frustumPlane.d = transform.m[15] - transform.m[13];
  6770. frustumPlane.normalize();
  6771. };
  6772. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6773. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6774. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6775. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6776. frustumPlane.d = transform.m[15] + transform.m[13];
  6777. frustumPlane.normalize();
  6778. };
  6779. /**
  6780. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6781. */
  6782. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6783. // Near
  6784. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6785. // Far
  6786. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6787. // Left
  6788. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6789. // Right
  6790. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6791. // Top
  6792. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6793. // Bottom
  6794. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6795. };
  6796. return Frustum;
  6797. }());
  6798. BABYLON.Frustum = Frustum;
  6799. /** Defines supported spaces */
  6800. var Space;
  6801. (function (Space) {
  6802. /** Local (object) space */
  6803. Space[Space["LOCAL"] = 0] = "LOCAL";
  6804. /** World space */
  6805. Space[Space["WORLD"] = 1] = "WORLD";
  6806. /** Bone space */
  6807. Space[Space["BONE"] = 2] = "BONE";
  6808. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6809. /** Defines the 3 main axes */
  6810. var Axis = /** @class */ (function () {
  6811. function Axis() {
  6812. }
  6813. /** X axis */
  6814. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6815. /** Y axis */
  6816. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6817. /** Z axis */
  6818. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6819. return Axis;
  6820. }());
  6821. BABYLON.Axis = Axis;
  6822. ;
  6823. var BezierCurve = /** @class */ (function () {
  6824. function BezierCurve() {
  6825. }
  6826. /**
  6827. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6828. */
  6829. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6830. // Extract X (which is equal to time here)
  6831. var f0 = 1 - 3 * x2 + 3 * x1;
  6832. var f1 = 3 * x2 - 6 * x1;
  6833. var f2 = 3 * x1;
  6834. var refinedT = t;
  6835. for (var i = 0; i < 5; i++) {
  6836. var refinedT2 = refinedT * refinedT;
  6837. var refinedT3 = refinedT2 * refinedT;
  6838. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6839. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6840. refinedT -= (x - t) * slope;
  6841. refinedT = Math.min(1, Math.max(0, refinedT));
  6842. }
  6843. // Resolve cubic bezier for the given x
  6844. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6845. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6846. Math.pow(refinedT, 3);
  6847. };
  6848. return BezierCurve;
  6849. }());
  6850. BABYLON.BezierCurve = BezierCurve;
  6851. /**
  6852. * Defines potential orientation for back face culling
  6853. */
  6854. var Orientation;
  6855. (function (Orientation) {
  6856. /**
  6857. * Clockwise
  6858. */
  6859. Orientation[Orientation["CW"] = 0] = "CW";
  6860. /** Counter clockwise */
  6861. Orientation[Orientation["CCW"] = 1] = "CCW";
  6862. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6863. /**
  6864. * Defines angle representation
  6865. */
  6866. var Angle = /** @class */ (function () {
  6867. /**
  6868. * Creates an Angle object of "radians" radians (float).
  6869. */
  6870. function Angle(radians) {
  6871. this._radians = radians;
  6872. if (this._radians < 0.0)
  6873. this._radians += (2.0 * Math.PI);
  6874. }
  6875. /**
  6876. * Get value in degrees
  6877. * @returns the Angle value in degrees (float)
  6878. */
  6879. Angle.prototype.degrees = function () {
  6880. return this._radians * 180.0 / Math.PI;
  6881. };
  6882. /**
  6883. * Get value in radians
  6884. * @returns the Angle value in radians (float)
  6885. */
  6886. Angle.prototype.radians = function () {
  6887. return this._radians;
  6888. };
  6889. /**
  6890. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6891. * @param a defines first vector
  6892. * @param b defines second vector
  6893. * @returns a new Angle
  6894. */
  6895. Angle.BetweenTwoPoints = function (a, b) {
  6896. var delta = b.subtract(a);
  6897. var theta = Math.atan2(delta.y, delta.x);
  6898. return new Angle(theta);
  6899. };
  6900. /**
  6901. * Gets a new Angle object from the given float in radians
  6902. * @param radians defines the angle value in radians
  6903. * @returns a new Angle
  6904. */
  6905. Angle.FromRadians = function (radians) {
  6906. return new Angle(radians);
  6907. };
  6908. /**
  6909. * Gets a new Angle object from the given float in degrees
  6910. * @param degrees defines the angle value in degrees
  6911. * @returns a new Angle
  6912. */
  6913. Angle.FromDegrees = function (degrees) {
  6914. return new Angle(degrees * Math.PI / 180.0);
  6915. };
  6916. return Angle;
  6917. }());
  6918. BABYLON.Angle = Angle;
  6919. var Arc2 = /** @class */ (function () {
  6920. /**
  6921. * Creates an Arc object from the three given points : start, middle and end.
  6922. */
  6923. function Arc2(startPoint, midPoint, endPoint) {
  6924. this.startPoint = startPoint;
  6925. this.midPoint = midPoint;
  6926. this.endPoint = endPoint;
  6927. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6928. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6929. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6930. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6931. 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);
  6932. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6933. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6934. var a1 = this.startAngle.degrees();
  6935. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6936. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6937. // angles correction
  6938. if (a2 - a1 > +180.0)
  6939. a2 -= 360.0;
  6940. if (a2 - a1 < -180.0)
  6941. a2 += 360.0;
  6942. if (a3 - a2 > +180.0)
  6943. a3 -= 360.0;
  6944. if (a3 - a2 < -180.0)
  6945. a3 += 360.0;
  6946. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6947. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6948. }
  6949. return Arc2;
  6950. }());
  6951. BABYLON.Arc2 = Arc2;
  6952. var Path2 = /** @class */ (function () {
  6953. /**
  6954. * Creates a Path2 object from the starting 2D coordinates x and y.
  6955. */
  6956. function Path2(x, y) {
  6957. this._points = new Array();
  6958. this._length = 0.0;
  6959. this.closed = false;
  6960. this._points.push(new Vector2(x, y));
  6961. }
  6962. /**
  6963. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6964. * Returns the updated Path2.
  6965. */
  6966. Path2.prototype.addLineTo = function (x, y) {
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var newPoint = new Vector2(x, y);
  6971. var previousPoint = this._points[this._points.length - 1];
  6972. this._points.push(newPoint);
  6973. this._length += newPoint.subtract(previousPoint).length();
  6974. return this;
  6975. };
  6976. /**
  6977. * 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.
  6978. * Returns the updated Path2.
  6979. */
  6980. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6981. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6982. if (this.closed) {
  6983. return this;
  6984. }
  6985. var startPoint = this._points[this._points.length - 1];
  6986. var midPoint = new Vector2(midX, midY);
  6987. var endPoint = new Vector2(endX, endY);
  6988. var arc = new Arc2(startPoint, midPoint, endPoint);
  6989. var increment = arc.angle.radians() / numberOfSegments;
  6990. if (arc.orientation === Orientation.CW)
  6991. increment *= -1;
  6992. var currentAngle = arc.startAngle.radians() + increment;
  6993. for (var i = 0; i < numberOfSegments; i++) {
  6994. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6995. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6996. this.addLineTo(x, y);
  6997. currentAngle += increment;
  6998. }
  6999. return this;
  7000. };
  7001. /**
  7002. * Closes the Path2.
  7003. * Returns the Path2.
  7004. */
  7005. Path2.prototype.close = function () {
  7006. this.closed = true;
  7007. return this;
  7008. };
  7009. /**
  7010. * Returns the Path2 total length (float).
  7011. */
  7012. Path2.prototype.length = function () {
  7013. var result = this._length;
  7014. if (!this.closed) {
  7015. var lastPoint = this._points[this._points.length - 1];
  7016. var firstPoint = this._points[0];
  7017. result += (firstPoint.subtract(lastPoint).length());
  7018. }
  7019. return result;
  7020. };
  7021. /**
  7022. * Returns the Path2 internal array of points.
  7023. */
  7024. Path2.prototype.getPoints = function () {
  7025. return this._points;
  7026. };
  7027. /**
  7028. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7029. */
  7030. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7031. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7032. return Vector2.Zero();
  7033. }
  7034. var lengthPosition = normalizedLengthPosition * this.length();
  7035. var previousOffset = 0;
  7036. for (var i = 0; i < this._points.length; i++) {
  7037. var j = (i + 1) % this._points.length;
  7038. var a = this._points[i];
  7039. var b = this._points[j];
  7040. var bToA = b.subtract(a);
  7041. var nextOffset = (bToA.length() + previousOffset);
  7042. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7043. var dir = bToA.normalize();
  7044. var localOffset = lengthPosition - previousOffset;
  7045. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7046. }
  7047. previousOffset = nextOffset;
  7048. }
  7049. return Vector2.Zero();
  7050. };
  7051. /**
  7052. * Returns a new Path2 starting at the coordinates (x, y).
  7053. */
  7054. Path2.StartingAt = function (x, y) {
  7055. return new Path2(x, y);
  7056. };
  7057. return Path2;
  7058. }());
  7059. BABYLON.Path2 = Path2;
  7060. var Path3D = /** @class */ (function () {
  7061. /**
  7062. * new Path3D(path, normal, raw)
  7063. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7064. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7065. * path : an array of Vector3, the curve axis of the Path3D
  7066. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7067. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7068. */
  7069. function Path3D(path, firstNormal, raw) {
  7070. if (firstNormal === void 0) { firstNormal = null; }
  7071. this.path = path;
  7072. this._curve = new Array();
  7073. this._distances = new Array();
  7074. this._tangents = new Array();
  7075. this._normals = new Array();
  7076. this._binormals = new Array();
  7077. for (var p = 0; p < path.length; p++) {
  7078. this._curve[p] = path[p].clone(); // hard copy
  7079. }
  7080. this._raw = raw || false;
  7081. this._compute(firstNormal);
  7082. }
  7083. /**
  7084. * Returns the Path3D array of successive Vector3 designing its curve.
  7085. */
  7086. Path3D.prototype.getCurve = function () {
  7087. return this._curve;
  7088. };
  7089. /**
  7090. * Returns an array populated with tangent vectors on each Path3D curve point.
  7091. */
  7092. Path3D.prototype.getTangents = function () {
  7093. return this._tangents;
  7094. };
  7095. /**
  7096. * Returns an array populated with normal vectors on each Path3D curve point.
  7097. */
  7098. Path3D.prototype.getNormals = function () {
  7099. return this._normals;
  7100. };
  7101. /**
  7102. * Returns an array populated with binormal vectors on each Path3D curve point.
  7103. */
  7104. Path3D.prototype.getBinormals = function () {
  7105. return this._binormals;
  7106. };
  7107. /**
  7108. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7109. */
  7110. Path3D.prototype.getDistances = function () {
  7111. return this._distances;
  7112. };
  7113. /**
  7114. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7115. * Returns the same object updated.
  7116. */
  7117. Path3D.prototype.update = function (path, firstNormal) {
  7118. if (firstNormal === void 0) { firstNormal = null; }
  7119. for (var p = 0; p < path.length; p++) {
  7120. this._curve[p].x = path[p].x;
  7121. this._curve[p].y = path[p].y;
  7122. this._curve[p].z = path[p].z;
  7123. }
  7124. this._compute(firstNormal);
  7125. return this;
  7126. };
  7127. // private function compute() : computes tangents, normals and binormals
  7128. Path3D.prototype._compute = function (firstNormal) {
  7129. var l = this._curve.length;
  7130. // first and last tangents
  7131. this._tangents[0] = this._getFirstNonNullVector(0);
  7132. if (!this._raw) {
  7133. this._tangents[0].normalize();
  7134. }
  7135. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7136. if (!this._raw) {
  7137. this._tangents[l - 1].normalize();
  7138. }
  7139. // normals and binormals at first point : arbitrary vector with _normalVector()
  7140. var tg0 = this._tangents[0];
  7141. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7142. this._normals[0] = pp0;
  7143. if (!this._raw) {
  7144. this._normals[0].normalize();
  7145. }
  7146. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7147. if (!this._raw) {
  7148. this._binormals[0].normalize();
  7149. }
  7150. this._distances[0] = 0.0;
  7151. // normals and binormals : next points
  7152. var prev; // previous vector (segment)
  7153. var cur; // current vector (segment)
  7154. var curTang; // current tangent
  7155. // previous normal
  7156. var prevBinor; // previous binormal
  7157. for (var i = 1; i < l; i++) {
  7158. // tangents
  7159. prev = this._getLastNonNullVector(i);
  7160. if (i < l - 1) {
  7161. cur = this._getFirstNonNullVector(i);
  7162. this._tangents[i] = prev.add(cur);
  7163. this._tangents[i].normalize();
  7164. }
  7165. this._distances[i] = this._distances[i - 1] + prev.length();
  7166. // normals and binormals
  7167. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7168. curTang = this._tangents[i];
  7169. prevBinor = this._binormals[i - 1];
  7170. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7171. if (!this._raw) {
  7172. this._normals[i].normalize();
  7173. }
  7174. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7175. if (!this._raw) {
  7176. this._binormals[i].normalize();
  7177. }
  7178. }
  7179. };
  7180. // private function getFirstNonNullVector(index)
  7181. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7182. Path3D.prototype._getFirstNonNullVector = function (index) {
  7183. var i = 1;
  7184. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7185. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7186. i++;
  7187. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7188. }
  7189. return nNVector;
  7190. };
  7191. // private function getLastNonNullVector(index)
  7192. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7193. Path3D.prototype._getLastNonNullVector = function (index) {
  7194. var i = 1;
  7195. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7196. while (nLVector.length() === 0 && index > i + 1) {
  7197. i++;
  7198. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7199. }
  7200. return nLVector;
  7201. };
  7202. // private function normalVector(v0, vt, va) :
  7203. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7204. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7205. Path3D.prototype._normalVector = function (v0, vt, va) {
  7206. var normal0;
  7207. var tgl = vt.length();
  7208. if (tgl === 0.0) {
  7209. tgl = 1.0;
  7210. }
  7211. if (va === undefined || va === null) {
  7212. var point;
  7213. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7214. point = new Vector3(0.0, -1.0, 0.0);
  7215. }
  7216. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7217. point = new Vector3(1.0, 0.0, 0.0);
  7218. }
  7219. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7220. point = new Vector3(0.0, 0.0, 1.0);
  7221. }
  7222. else {
  7223. point = Vector3.Zero();
  7224. }
  7225. normal0 = Vector3.Cross(vt, point);
  7226. }
  7227. else {
  7228. normal0 = Vector3.Cross(vt, va);
  7229. Vector3.CrossToRef(normal0, vt, normal0);
  7230. }
  7231. normal0.normalize();
  7232. return normal0;
  7233. };
  7234. return Path3D;
  7235. }());
  7236. BABYLON.Path3D = Path3D;
  7237. var Curve3 = /** @class */ (function () {
  7238. /**
  7239. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7240. * A Curve3 is designed from a series of successive Vector3.
  7241. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7242. */
  7243. function Curve3(points) {
  7244. this._length = 0.0;
  7245. this._points = points;
  7246. this._length = this._computeLength(points);
  7247. }
  7248. /**
  7249. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7250. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7251. * @param v1 (Vector3) the control point
  7252. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7253. * @param nbPoints (integer) the wanted number of points in the curve
  7254. */
  7255. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7256. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7257. var bez = new Array();
  7258. var equation = function (t, val0, val1, val2) {
  7259. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7260. return res;
  7261. };
  7262. for (var i = 0; i <= nbPoints; i++) {
  7263. 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)));
  7264. }
  7265. return new Curve3(bez);
  7266. };
  7267. /**
  7268. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7269. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7270. * @param v1 (Vector3) the first control point
  7271. * @param v2 (Vector3) the second control point
  7272. * @param v3 (Vector3) the end point of the Cubic Bezier
  7273. * @param nbPoints (integer) the wanted number of points in the curve
  7274. */
  7275. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7276. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7277. var bez = new Array();
  7278. var equation = function (t, val0, val1, val2, val3) {
  7279. 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;
  7280. return res;
  7281. };
  7282. for (var i = 0; i <= nbPoints; i++) {
  7283. 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)));
  7284. }
  7285. return new Curve3(bez);
  7286. };
  7287. /**
  7288. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7289. * @param p1 (Vector3) the origin point of the Hermite Spline
  7290. * @param t1 (Vector3) the tangent vector at the origin point
  7291. * @param p2 (Vector3) the end point of the Hermite Spline
  7292. * @param t2 (Vector3) the tangent vector at the end point
  7293. * @param nbPoints (integer) the wanted number of points in the curve
  7294. */
  7295. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7296. var hermite = new Array();
  7297. var step = 1.0 / nbPoints;
  7298. for (var i = 0; i <= nbPoints; i++) {
  7299. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7300. }
  7301. return new Curve3(hermite);
  7302. };
  7303. /**
  7304. * Returns a Curve3 object along a CatmullRom Spline curve :
  7305. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7306. * @param nbPoints (integer) the wanted number of points between each curve control points
  7307. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7308. */
  7309. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7310. var catmullRom = new Array();
  7311. var step = 1.0 / nbPoints;
  7312. var amount = 0.0;
  7313. if (closed) {
  7314. var pointsCount = points.length;
  7315. for (var i = 0; i < pointsCount; i++) {
  7316. amount = 0;
  7317. for (var c = 0; c < nbPoints; c++) {
  7318. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7319. amount += step;
  7320. }
  7321. }
  7322. catmullRom.push(catmullRom[0]);
  7323. }
  7324. else {
  7325. var totalPoints = new Array();
  7326. totalPoints.push(points[0].clone());
  7327. Array.prototype.push.apply(totalPoints, points);
  7328. totalPoints.push(points[points.length - 1].clone());
  7329. for (var i = 0; i < totalPoints.length - 3; i++) {
  7330. amount = 0;
  7331. for (var c = 0; c < nbPoints; c++) {
  7332. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7333. amount += step;
  7334. }
  7335. }
  7336. i--;
  7337. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7338. }
  7339. return new Curve3(catmullRom);
  7340. };
  7341. /**
  7342. * Returns the Curve3 stored array of successive Vector3
  7343. */
  7344. Curve3.prototype.getPoints = function () {
  7345. return this._points;
  7346. };
  7347. /**
  7348. * Returns the computed length (float) of the curve.
  7349. */
  7350. Curve3.prototype.length = function () {
  7351. return this._length;
  7352. };
  7353. /**
  7354. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7355. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7356. * curveA and curveB keep unchanged.
  7357. */
  7358. Curve3.prototype.continue = function (curve) {
  7359. var lastPoint = this._points[this._points.length - 1];
  7360. var continuedPoints = this._points.slice();
  7361. var curvePoints = curve.getPoints();
  7362. for (var i = 1; i < curvePoints.length; i++) {
  7363. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7364. }
  7365. var continuedCurve = new Curve3(continuedPoints);
  7366. return continuedCurve;
  7367. };
  7368. Curve3.prototype._computeLength = function (path) {
  7369. var l = 0;
  7370. for (var i = 1; i < path.length; i++) {
  7371. l += (path[i].subtract(path[i - 1])).length();
  7372. }
  7373. return l;
  7374. };
  7375. return Curve3;
  7376. }());
  7377. BABYLON.Curve3 = Curve3;
  7378. // Vertex formats
  7379. var PositionNormalVertex = /** @class */ (function () {
  7380. function PositionNormalVertex(position, normal) {
  7381. if (position === void 0) { position = Vector3.Zero(); }
  7382. if (normal === void 0) { normal = Vector3.Up(); }
  7383. this.position = position;
  7384. this.normal = normal;
  7385. }
  7386. PositionNormalVertex.prototype.clone = function () {
  7387. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7388. };
  7389. return PositionNormalVertex;
  7390. }());
  7391. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7392. var PositionNormalTextureVertex = /** @class */ (function () {
  7393. function PositionNormalTextureVertex(position, normal, uv) {
  7394. if (position === void 0) { position = Vector3.Zero(); }
  7395. if (normal === void 0) { normal = Vector3.Up(); }
  7396. if (uv === void 0) { uv = Vector2.Zero(); }
  7397. this.position = position;
  7398. this.normal = normal;
  7399. this.uv = uv;
  7400. }
  7401. PositionNormalTextureVertex.prototype.clone = function () {
  7402. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7403. };
  7404. return PositionNormalTextureVertex;
  7405. }());
  7406. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7407. // Temporary pre-allocated objects for engine internal use
  7408. // usage in any internal function :
  7409. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7410. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7411. var Tmp = /** @class */ (function () {
  7412. function Tmp() {
  7413. }
  7414. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7415. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7416. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7417. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7418. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7419. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7420. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7421. Matrix.Zero(), Matrix.Zero(),
  7422. Matrix.Zero(), Matrix.Zero(),
  7423. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7424. return Tmp;
  7425. }());
  7426. BABYLON.Tmp = Tmp;
  7427. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7428. var MathTmp = /** @class */ (function () {
  7429. function MathTmp() {
  7430. }
  7431. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7432. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7433. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7434. return MathTmp;
  7435. }());
  7436. })(BABYLON || (BABYLON = {}));
  7437. //# sourceMappingURL=babylon.math.js.map
  7438. var BABYLON;
  7439. (function (BABYLON) {
  7440. var Scalar = /** @class */ (function () {
  7441. function Scalar() {
  7442. }
  7443. /**
  7444. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7445. */
  7446. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7447. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7448. var num = a - b;
  7449. return -epsilon <= num && num <= epsilon;
  7450. };
  7451. /**
  7452. * Returns a string : the upper case translation of the number i to hexadecimal.
  7453. */
  7454. Scalar.ToHex = function (i) {
  7455. var str = i.toString(16);
  7456. if (i <= 15) {
  7457. return ("0" + str).toUpperCase();
  7458. }
  7459. return str.toUpperCase();
  7460. };
  7461. /**
  7462. * Returns -1 if value is negative and +1 is value is positive.
  7463. * Returns the value itself if it's equal to zero.
  7464. */
  7465. Scalar.Sign = function (value) {
  7466. value = +value; // convert to a number
  7467. if (value === 0 || isNaN(value))
  7468. return value;
  7469. return value > 0 ? 1 : -1;
  7470. };
  7471. /**
  7472. * Returns the value itself if it's between min and max.
  7473. * Returns min if the value is lower than min.
  7474. * Returns max if the value is greater than max.
  7475. */
  7476. Scalar.Clamp = function (value, min, max) {
  7477. if (min === void 0) { min = 0; }
  7478. if (max === void 0) { max = 1; }
  7479. return Math.min(max, Math.max(min, value));
  7480. };
  7481. /**
  7482. * Returns the log2 of value.
  7483. */
  7484. Scalar.Log2 = function (value) {
  7485. return Math.log(value) * Math.LOG2E;
  7486. };
  7487. /**
  7488. * Loops the value, so that it is never larger than length and never smaller than 0.
  7489. *
  7490. * This is similar to the modulo operator but it works with floating point numbers.
  7491. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7492. * With t = 5 and length = 2.5, the result would be 0.0.
  7493. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7494. */
  7495. Scalar.Repeat = function (value, length) {
  7496. return value - Math.floor(value / length) * length;
  7497. };
  7498. /**
  7499. * Normalize the value between 0.0 and 1.0 using min and max values
  7500. */
  7501. Scalar.Normalize = function (value, min, max) {
  7502. return (value - min) / (max - min);
  7503. };
  7504. /**
  7505. * Denormalize the value from 0.0 and 1.0 using min and max values
  7506. */
  7507. Scalar.Denormalize = function (normalized, min, max) {
  7508. return (normalized * (max - min) + min);
  7509. };
  7510. /**
  7511. * Calculates the shortest difference between two given angles given in degrees.
  7512. */
  7513. Scalar.DeltaAngle = function (current, target) {
  7514. var num = Scalar.Repeat(target - current, 360.0);
  7515. if (num > 180.0) {
  7516. num -= 360.0;
  7517. }
  7518. return num;
  7519. };
  7520. /**
  7521. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7522. *
  7523. * The returned value will move back and forth between 0 and length
  7524. */
  7525. Scalar.PingPong = function (tx, length) {
  7526. var t = Scalar.Repeat(tx, length * 2.0);
  7527. return length - Math.abs(t - length);
  7528. };
  7529. /**
  7530. * Interpolates between min and max with smoothing at the limits.
  7531. *
  7532. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7533. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7534. */
  7535. Scalar.SmoothStep = function (from, to, tx) {
  7536. var t = Scalar.Clamp(tx);
  7537. t = -2.0 * t * t * t + 3.0 * t * t;
  7538. return to * t + from * (1.0 - t);
  7539. };
  7540. /**
  7541. * Moves a value current towards target.
  7542. *
  7543. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7544. * Negative values of maxDelta pushes the value away from target.
  7545. */
  7546. Scalar.MoveTowards = function (current, target, maxDelta) {
  7547. var result = 0;
  7548. if (Math.abs(target - current) <= maxDelta) {
  7549. result = target;
  7550. }
  7551. else {
  7552. result = current + Scalar.Sign(target - current) * maxDelta;
  7553. }
  7554. return result;
  7555. };
  7556. /**
  7557. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7558. *
  7559. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7560. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7561. */
  7562. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7563. var num = Scalar.DeltaAngle(current, target);
  7564. var result = 0;
  7565. if (-maxDelta < num && num < maxDelta) {
  7566. result = target;
  7567. }
  7568. else {
  7569. target = current + num;
  7570. result = Scalar.MoveTowards(current, target, maxDelta);
  7571. }
  7572. return result;
  7573. };
  7574. /**
  7575. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7576. */
  7577. Scalar.Lerp = function (start, end, amount) {
  7578. return start + ((end - start) * amount);
  7579. };
  7580. /**
  7581. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7582. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7583. */
  7584. Scalar.LerpAngle = function (start, end, amount) {
  7585. var num = Scalar.Repeat(end - start, 360.0);
  7586. if (num > 180.0) {
  7587. num -= 360.0;
  7588. }
  7589. return start + num * Scalar.Clamp(amount);
  7590. };
  7591. /**
  7592. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7593. */
  7594. Scalar.InverseLerp = function (a, b, value) {
  7595. var result = 0;
  7596. if (a != b) {
  7597. result = Scalar.Clamp((value - a) / (b - a));
  7598. }
  7599. else {
  7600. result = 0.0;
  7601. }
  7602. return result;
  7603. };
  7604. /**
  7605. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7606. */
  7607. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7608. var squared = amount * amount;
  7609. var cubed = amount * squared;
  7610. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7611. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7612. var part3 = (cubed - (2.0 * squared)) + amount;
  7613. var part4 = cubed - squared;
  7614. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7615. };
  7616. /**
  7617. * Returns a random float number between and min and max values
  7618. */
  7619. Scalar.RandomRange = function (min, max) {
  7620. if (min === max)
  7621. return min;
  7622. return ((Math.random() * (max - min)) + min);
  7623. };
  7624. /**
  7625. * This function returns percentage of a number in a given range.
  7626. *
  7627. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7628. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7629. */
  7630. Scalar.RangeToPercent = function (number, min, max) {
  7631. return ((number - min) / (max - min));
  7632. };
  7633. /**
  7634. * This function returns number that corresponds to the percentage in a given range.
  7635. *
  7636. * PercentToRange(0.34,0,100) will return 34.
  7637. */
  7638. Scalar.PercentToRange = function (percent, min, max) {
  7639. return ((max - min) * percent + min);
  7640. };
  7641. /**
  7642. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7643. * @param angle The angle to normalize in radian.
  7644. * @return The converted angle.
  7645. */
  7646. Scalar.NormalizeRadians = function (angle) {
  7647. // More precise but slower version kept for reference.
  7648. // angle = angle % Tools.TwoPi;
  7649. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7650. //if (angle > Math.PI) {
  7651. // angle -= Tools.TwoPi;
  7652. //}
  7653. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7654. return angle;
  7655. };
  7656. /**
  7657. * Two pi constants convenient for computation.
  7658. */
  7659. Scalar.TwoPi = Math.PI * 2;
  7660. return Scalar;
  7661. }());
  7662. BABYLON.Scalar = Scalar;
  7663. })(BABYLON || (BABYLON = {}));
  7664. //# sourceMappingURL=babylon.math.scalar.js.map
  7665. //# sourceMappingURL=babylon.mixins.js.map
  7666. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7667. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7668. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7669. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7670. //# sourceMappingURL=babylon.webgl2.js.map
  7671. var BABYLON;
  7672. (function (BABYLON) {
  7673. var __decoratorInitialStore = {};
  7674. var __mergedStore = {};
  7675. var _copySource = function (creationFunction, source, instanciate) {
  7676. var destination = creationFunction();
  7677. // Tags
  7678. if (BABYLON.Tags) {
  7679. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7680. }
  7681. var classStore = getMergedStore(destination);
  7682. // Properties
  7683. for (var property in classStore) {
  7684. var propertyDescriptor = classStore[property];
  7685. var sourceProperty = source[property];
  7686. var propertyType = propertyDescriptor.type;
  7687. if (sourceProperty !== undefined && sourceProperty !== null) {
  7688. switch (propertyType) {
  7689. case 0: // Value
  7690. case 6: // Mesh reference
  7691. case 11: // Camera reference
  7692. destination[property] = sourceProperty;
  7693. break;
  7694. case 1: // Texture
  7695. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7696. break;
  7697. case 2: // Color3
  7698. case 3: // FresnelParameters
  7699. case 4: // Vector2
  7700. case 5: // Vector3
  7701. case 7: // Color Curves
  7702. case 10: // Quaternion
  7703. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7704. break;
  7705. }
  7706. }
  7707. }
  7708. return destination;
  7709. };
  7710. function getDirectStore(target) {
  7711. var classKey = target.getClassName();
  7712. if (!__decoratorInitialStore[classKey]) {
  7713. __decoratorInitialStore[classKey] = {};
  7714. }
  7715. return __decoratorInitialStore[classKey];
  7716. }
  7717. /**
  7718. * Return the list of properties flagged as serializable
  7719. * @param target: host object
  7720. */
  7721. function getMergedStore(target) {
  7722. var classKey = target.getClassName();
  7723. if (__mergedStore[classKey]) {
  7724. return __mergedStore[classKey];
  7725. }
  7726. __mergedStore[classKey] = {};
  7727. var store = __mergedStore[classKey];
  7728. var currentTarget = target;
  7729. var currentKey = classKey;
  7730. while (currentKey) {
  7731. var initialStore = __decoratorInitialStore[currentKey];
  7732. for (var property in initialStore) {
  7733. store[property] = initialStore[property];
  7734. }
  7735. var parent_1 = void 0;
  7736. var done = false;
  7737. do {
  7738. parent_1 = Object.getPrototypeOf(currentTarget);
  7739. if (!parent_1.getClassName) {
  7740. done = true;
  7741. break;
  7742. }
  7743. if (parent_1.getClassName() !== currentKey) {
  7744. break;
  7745. }
  7746. currentTarget = parent_1;
  7747. } while (parent_1);
  7748. if (done) {
  7749. break;
  7750. }
  7751. currentKey = parent_1.getClassName();
  7752. currentTarget = parent_1;
  7753. }
  7754. return store;
  7755. }
  7756. function generateSerializableMember(type, sourceName) {
  7757. return function (target, propertyKey) {
  7758. var classStore = getDirectStore(target);
  7759. if (!classStore[propertyKey]) {
  7760. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7761. }
  7762. };
  7763. }
  7764. function generateExpandMember(setCallback, targetKey) {
  7765. if (targetKey === void 0) { targetKey = null; }
  7766. return function (target, propertyKey) {
  7767. var key = targetKey || ("_" + propertyKey);
  7768. Object.defineProperty(target, propertyKey, {
  7769. get: function () {
  7770. return this[key];
  7771. },
  7772. set: function (value) {
  7773. if (this[key] === value) {
  7774. return;
  7775. }
  7776. this[key] = value;
  7777. target[setCallback].apply(this);
  7778. },
  7779. enumerable: true,
  7780. configurable: true
  7781. });
  7782. };
  7783. }
  7784. function expandToProperty(callback, targetKey) {
  7785. if (targetKey === void 0) { targetKey = null; }
  7786. return generateExpandMember(callback, targetKey);
  7787. }
  7788. BABYLON.expandToProperty = expandToProperty;
  7789. function serialize(sourceName) {
  7790. return generateSerializableMember(0, sourceName); // value member
  7791. }
  7792. BABYLON.serialize = serialize;
  7793. function serializeAsTexture(sourceName) {
  7794. return generateSerializableMember(1, sourceName); // texture member
  7795. }
  7796. BABYLON.serializeAsTexture = serializeAsTexture;
  7797. function serializeAsColor3(sourceName) {
  7798. return generateSerializableMember(2, sourceName); // color3 member
  7799. }
  7800. BABYLON.serializeAsColor3 = serializeAsColor3;
  7801. function serializeAsFresnelParameters(sourceName) {
  7802. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7803. }
  7804. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7805. function serializeAsVector2(sourceName) {
  7806. return generateSerializableMember(4, sourceName); // vector2 member
  7807. }
  7808. BABYLON.serializeAsVector2 = serializeAsVector2;
  7809. function serializeAsVector3(sourceName) {
  7810. return generateSerializableMember(5, sourceName); // vector3 member
  7811. }
  7812. BABYLON.serializeAsVector3 = serializeAsVector3;
  7813. function serializeAsMeshReference(sourceName) {
  7814. return generateSerializableMember(6, sourceName); // mesh reference member
  7815. }
  7816. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7817. function serializeAsColorCurves(sourceName) {
  7818. return generateSerializableMember(7, sourceName); // color curves
  7819. }
  7820. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7821. function serializeAsColor4(sourceName) {
  7822. return generateSerializableMember(8, sourceName); // color 4
  7823. }
  7824. BABYLON.serializeAsColor4 = serializeAsColor4;
  7825. function serializeAsImageProcessingConfiguration(sourceName) {
  7826. return generateSerializableMember(9, sourceName); // image processing
  7827. }
  7828. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7829. function serializeAsQuaternion(sourceName) {
  7830. return generateSerializableMember(10, sourceName); // quaternion member
  7831. }
  7832. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7833. /**
  7834. * Decorator used to define property that can be serialized as reference to a camera
  7835. * @param sourceName defines the name of the property to decorate
  7836. */
  7837. function serializeAsCameraReference(sourceName) {
  7838. return generateSerializableMember(11, sourceName); // camera reference member
  7839. }
  7840. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7841. var SerializationHelper = /** @class */ (function () {
  7842. function SerializationHelper() {
  7843. }
  7844. SerializationHelper.Serialize = function (entity, serializationObject) {
  7845. if (!serializationObject) {
  7846. serializationObject = {};
  7847. }
  7848. // Tags
  7849. if (BABYLON.Tags) {
  7850. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7851. }
  7852. var serializedProperties = getMergedStore(entity);
  7853. // Properties
  7854. for (var property in serializedProperties) {
  7855. var propertyDescriptor = serializedProperties[property];
  7856. var targetPropertyName = propertyDescriptor.sourceName || property;
  7857. var propertyType = propertyDescriptor.type;
  7858. var sourceProperty = entity[property];
  7859. if (sourceProperty !== undefined && sourceProperty !== null) {
  7860. switch (propertyType) {
  7861. case 0: // Value
  7862. serializationObject[targetPropertyName] = sourceProperty;
  7863. break;
  7864. case 1: // Texture
  7865. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7866. break;
  7867. case 2: // Color3
  7868. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7869. break;
  7870. case 3: // FresnelParameters
  7871. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7872. break;
  7873. case 4: // Vector2
  7874. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7875. break;
  7876. case 5: // Vector3
  7877. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7878. break;
  7879. case 6: // Mesh reference
  7880. serializationObject[targetPropertyName] = sourceProperty.id;
  7881. break;
  7882. case 7: // Color Curves
  7883. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7884. break;
  7885. case 8: // Color 4
  7886. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7887. break;
  7888. case 9: // Image Processing
  7889. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7890. break;
  7891. case 10: // Quaternion
  7892. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7893. break;
  7894. case 11: // Camera reference
  7895. serializationObject[targetPropertyName] = sourceProperty.id;
  7896. break;
  7897. }
  7898. }
  7899. }
  7900. return serializationObject;
  7901. };
  7902. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7903. if (rootUrl === void 0) { rootUrl = null; }
  7904. var destination = creationFunction();
  7905. if (!rootUrl) {
  7906. rootUrl = "";
  7907. }
  7908. // Tags
  7909. if (BABYLON.Tags) {
  7910. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7911. }
  7912. var classStore = getMergedStore(destination);
  7913. // Properties
  7914. for (var property in classStore) {
  7915. var propertyDescriptor = classStore[property];
  7916. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7917. var propertyType = propertyDescriptor.type;
  7918. if (sourceProperty !== undefined && sourceProperty !== null) {
  7919. var dest = destination;
  7920. switch (propertyType) {
  7921. case 0: // Value
  7922. dest[property] = sourceProperty;
  7923. break;
  7924. case 1: // Texture
  7925. if (scene) {
  7926. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7927. }
  7928. break;
  7929. case 2: // Color3
  7930. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7931. break;
  7932. case 3: // FresnelParameters
  7933. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7934. break;
  7935. case 4: // Vector2
  7936. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7937. break;
  7938. case 5: // Vector3
  7939. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7940. break;
  7941. case 6: // Mesh reference
  7942. if (scene) {
  7943. dest[property] = scene.getLastMeshByID(sourceProperty);
  7944. }
  7945. break;
  7946. case 7: // Color Curves
  7947. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7948. break;
  7949. case 8: // Color 4
  7950. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7951. break;
  7952. case 9: // Image Processing
  7953. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7954. break;
  7955. case 10: // Quaternion
  7956. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7957. break;
  7958. case 11: // Camera reference
  7959. if (scene) {
  7960. dest[property] = scene.getCameraByID(sourceProperty);
  7961. }
  7962. break;
  7963. }
  7964. }
  7965. }
  7966. return destination;
  7967. };
  7968. SerializationHelper.Clone = function (creationFunction, source) {
  7969. return _copySource(creationFunction, source, false);
  7970. };
  7971. SerializationHelper.Instanciate = function (creationFunction, source) {
  7972. return _copySource(creationFunction, source, true);
  7973. };
  7974. return SerializationHelper;
  7975. }());
  7976. BABYLON.SerializationHelper = SerializationHelper;
  7977. })(BABYLON || (BABYLON = {}));
  7978. //# sourceMappingURL=babylon.decorators.js.map
  7979. var BABYLON;
  7980. (function (BABYLON) {
  7981. /**
  7982. * Wrapper class for promise with external resolve and reject.
  7983. */
  7984. var Deferred = /** @class */ (function () {
  7985. /**
  7986. * Constructor for this deferred object.
  7987. */
  7988. function Deferred() {
  7989. var _this = this;
  7990. this.promise = new Promise(function (resolve, reject) {
  7991. _this._resolve = resolve;
  7992. _this._reject = reject;
  7993. });
  7994. }
  7995. Object.defineProperty(Deferred.prototype, "resolve", {
  7996. /**
  7997. * The resolve method of the promise associated with this deferred object.
  7998. */
  7999. get: function () {
  8000. return this._resolve;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Deferred.prototype, "reject", {
  8006. /**
  8007. * The reject method of the promise associated with this deferred object.
  8008. */
  8009. get: function () {
  8010. return this._reject;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. return Deferred;
  8016. }());
  8017. BABYLON.Deferred = Deferred;
  8018. })(BABYLON || (BABYLON = {}));
  8019. //# sourceMappingURL=babylon.deferred.js.map
  8020. var BABYLON;
  8021. (function (BABYLON) {
  8022. /**
  8023. * A class serves as a medium between the observable and its observers
  8024. */
  8025. var EventState = /** @class */ (function () {
  8026. /**
  8027. * Create a new EventState
  8028. * @param mask defines the mask associated with this state
  8029. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8030. * @param target defines the original target of the state
  8031. * @param currentTarget defines the current target of the state
  8032. */
  8033. function EventState(mask, skipNextObservers, target, currentTarget) {
  8034. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8035. this.initalize(mask, skipNextObservers, target, currentTarget);
  8036. }
  8037. /**
  8038. * Initialize the current event state
  8039. * @param mask defines the mask associated with this state
  8040. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8041. * @param target defines the original target of the state
  8042. * @param currentTarget defines the current target of the state
  8043. * @returns the current event state
  8044. */
  8045. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8046. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8047. this.mask = mask;
  8048. this.skipNextObservers = skipNextObservers;
  8049. this.target = target;
  8050. this.currentTarget = currentTarget;
  8051. return this;
  8052. };
  8053. return EventState;
  8054. }());
  8055. BABYLON.EventState = EventState;
  8056. /**
  8057. * Represent an Observer registered to a given Observable object.
  8058. */
  8059. var Observer = /** @class */ (function () {
  8060. /**
  8061. * Creates a new observer
  8062. * @param callback defines the callback to call when the observer is notified
  8063. * @param mask defines the mask of the observer (used to filter notifications)
  8064. * @param scope defines the current scope used to restore the JS context
  8065. */
  8066. function Observer(
  8067. /**
  8068. * Defines the callback to call when the observer is notified
  8069. */
  8070. callback,
  8071. /**
  8072. * Defines the mask of the observer (used to filter notifications)
  8073. */
  8074. mask,
  8075. /**
  8076. * Defines the current scope used to restore the JS context
  8077. */
  8078. scope) {
  8079. if (scope === void 0) { scope = null; }
  8080. this.callback = callback;
  8081. this.mask = mask;
  8082. this.scope = scope;
  8083. /** @hidden */
  8084. this._willBeUnregistered = false;
  8085. /**
  8086. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8087. */
  8088. this.unregisterOnNextCall = false;
  8089. }
  8090. return Observer;
  8091. }());
  8092. BABYLON.Observer = Observer;
  8093. /**
  8094. * Represent a list of observers registered to multiple Observables object.
  8095. */
  8096. var MultiObserver = /** @class */ (function () {
  8097. function MultiObserver() {
  8098. }
  8099. /**
  8100. * Release associated resources
  8101. */
  8102. MultiObserver.prototype.dispose = function () {
  8103. if (this._observers && this._observables) {
  8104. for (var index = 0; index < this._observers.length; index++) {
  8105. this._observables[index].remove(this._observers[index]);
  8106. }
  8107. }
  8108. this._observers = null;
  8109. this._observables = null;
  8110. };
  8111. /**
  8112. * Raise a callback when one of the observable will notify
  8113. * @param observables defines a list of observables to watch
  8114. * @param callback defines the callback to call on notification
  8115. * @param mask defines the mask used to filter notifications
  8116. * @param scope defines the current scope used to restore the JS context
  8117. * @returns the new MultiObserver
  8118. */
  8119. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8120. if (mask === void 0) { mask = -1; }
  8121. if (scope === void 0) { scope = null; }
  8122. var result = new MultiObserver();
  8123. result._observers = new Array();
  8124. result._observables = observables;
  8125. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8126. var observable = observables_1[_i];
  8127. var observer = observable.add(callback, mask, false, scope);
  8128. if (observer) {
  8129. result._observers.push(observer);
  8130. }
  8131. }
  8132. return result;
  8133. };
  8134. return MultiObserver;
  8135. }());
  8136. BABYLON.MultiObserver = MultiObserver;
  8137. /**
  8138. * The Observable class is a simple implementation of the Observable pattern.
  8139. *
  8140. * 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.
  8141. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8142. * 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).
  8143. * 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.
  8144. */
  8145. var Observable = /** @class */ (function () {
  8146. /**
  8147. * Creates a new observable
  8148. * @param onObserverAdded defines a callback to call when a new observer is added
  8149. */
  8150. function Observable(onObserverAdded) {
  8151. this._observers = new Array();
  8152. this._eventState = new EventState(0);
  8153. if (onObserverAdded) {
  8154. this._onObserverAdded = onObserverAdded;
  8155. }
  8156. }
  8157. /**
  8158. * Create a new Observer with the specified callback
  8159. * @param callback the callback that will be executed for that Observer
  8160. * @param mask the mask used to filter observers
  8161. * @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.
  8162. * @param scope optional scope for the callback to be called from
  8163. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8164. * @returns the new observer created for the callback
  8165. */
  8166. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8167. if (mask === void 0) { mask = -1; }
  8168. if (insertFirst === void 0) { insertFirst = false; }
  8169. if (scope === void 0) { scope = null; }
  8170. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8171. if (!callback) {
  8172. return null;
  8173. }
  8174. var observer = new Observer(callback, mask, scope);
  8175. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8176. if (insertFirst) {
  8177. this._observers.unshift(observer);
  8178. }
  8179. else {
  8180. this._observers.push(observer);
  8181. }
  8182. if (this._onObserverAdded) {
  8183. this._onObserverAdded(observer);
  8184. }
  8185. return observer;
  8186. };
  8187. /**
  8188. * Create a new Observer with the specified callback and unregisters after the next notification
  8189. * @param callback the callback that will be executed for that Observer
  8190. * @returns the new observer created for the callback
  8191. */
  8192. Observable.prototype.addOnce = function (callback) {
  8193. return this.add(callback, undefined, undefined, undefined, true);
  8194. };
  8195. /**
  8196. * Remove an Observer from the Observable object
  8197. * @param observer the instance of the Observer to remove
  8198. * @returns false if it doesn't belong to this Observable
  8199. */
  8200. Observable.prototype.remove = function (observer) {
  8201. if (!observer) {
  8202. return false;
  8203. }
  8204. var index = this._observers.indexOf(observer);
  8205. if (index !== -1) {
  8206. this._observers.splice(index, 1);
  8207. return true;
  8208. }
  8209. return false;
  8210. };
  8211. /**
  8212. * Remove a callback from the Observable object
  8213. * @param callback the callback to remove
  8214. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8215. * @returns false if it doesn't belong to this Observable
  8216. */
  8217. Observable.prototype.removeCallback = function (callback, scope) {
  8218. for (var index = 0; index < this._observers.length; index++) {
  8219. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8220. this._observers.splice(index, 1);
  8221. return true;
  8222. }
  8223. }
  8224. return false;
  8225. };
  8226. Observable.prototype._deferUnregister = function (observer) {
  8227. var _this = this;
  8228. observer.unregisterOnNextCall = false;
  8229. observer._willBeUnregistered = true;
  8230. BABYLON.Tools.SetImmediate(function () {
  8231. _this.remove(observer);
  8232. });
  8233. };
  8234. /**
  8235. * Notify all Observers by calling their respective callback with the given data
  8236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8237. * @param eventData defines the data to send to all observers
  8238. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8239. * @param target defines the original target of the state
  8240. * @param currentTarget defines the current target of the state
  8241. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8242. */
  8243. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8244. if (mask === void 0) { mask = -1; }
  8245. if (!this._observers.length) {
  8246. return true;
  8247. }
  8248. var state = this._eventState;
  8249. state.mask = mask;
  8250. state.target = target;
  8251. state.currentTarget = currentTarget;
  8252. state.skipNextObservers = false;
  8253. state.lastReturnValue = eventData;
  8254. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8255. var obs = _a[_i];
  8256. if (obs._willBeUnregistered) {
  8257. continue;
  8258. }
  8259. if (obs.mask & mask) {
  8260. if (obs.scope) {
  8261. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8262. }
  8263. else {
  8264. state.lastReturnValue = obs.callback(eventData, state);
  8265. }
  8266. if (obs.unregisterOnNextCall) {
  8267. this._deferUnregister(obs);
  8268. }
  8269. }
  8270. if (state.skipNextObservers) {
  8271. return false;
  8272. }
  8273. }
  8274. return true;
  8275. };
  8276. /**
  8277. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8278. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8279. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8280. * and it is crucial that all callbacks will be executed.
  8281. * The order of the callbacks is kept, callbacks are not executed parallel.
  8282. *
  8283. * @param eventData The data to be sent to each callback
  8284. * @param mask is used to filter observers defaults to -1
  8285. * @param target defines the callback target (see EventState)
  8286. * @param currentTarget defines he current object in the bubbling phase
  8287. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8288. */
  8289. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8290. var _this = this;
  8291. if (mask === void 0) { mask = -1; }
  8292. // create an empty promise
  8293. var p = Promise.resolve(eventData);
  8294. // no observers? return this promise.
  8295. if (!this._observers.length) {
  8296. return p;
  8297. }
  8298. var state = this._eventState;
  8299. state.mask = mask;
  8300. state.target = target;
  8301. state.currentTarget = currentTarget;
  8302. state.skipNextObservers = false;
  8303. // execute one callback after another (not using Promise.all, the order is important)
  8304. this._observers.forEach(function (obs) {
  8305. if (state.skipNextObservers) {
  8306. return;
  8307. }
  8308. if (obs._willBeUnregistered) {
  8309. return;
  8310. }
  8311. if (obs.mask & mask) {
  8312. if (obs.scope) {
  8313. p = p.then(function (lastReturnedValue) {
  8314. state.lastReturnValue = lastReturnedValue;
  8315. return obs.callback.apply(obs.scope, [eventData, state]);
  8316. });
  8317. }
  8318. else {
  8319. p = p.then(function (lastReturnedValue) {
  8320. state.lastReturnValue = lastReturnedValue;
  8321. return obs.callback(eventData, state);
  8322. });
  8323. }
  8324. if (obs.unregisterOnNextCall) {
  8325. _this._deferUnregister(obs);
  8326. }
  8327. }
  8328. });
  8329. // return the eventData
  8330. return p.then(function () { return eventData; });
  8331. };
  8332. /**
  8333. * Notify a specific observer
  8334. * @param observer defines the observer to notify
  8335. * @param eventData defines the data to be sent to each callback
  8336. * @param mask is used to filter observers defaults to -1
  8337. */
  8338. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8339. if (mask === void 0) { mask = -1; }
  8340. var state = this._eventState;
  8341. state.mask = mask;
  8342. state.skipNextObservers = false;
  8343. observer.callback(eventData, state);
  8344. };
  8345. /**
  8346. * Gets a boolean indicating if the observable has at least one observer
  8347. * @returns true is the Observable has at least one Observer registered
  8348. */
  8349. Observable.prototype.hasObservers = function () {
  8350. return this._observers.length > 0;
  8351. };
  8352. /**
  8353. * Clear the list of observers
  8354. */
  8355. Observable.prototype.clear = function () {
  8356. this._observers = new Array();
  8357. this._onObserverAdded = null;
  8358. };
  8359. /**
  8360. * Clone the current observable
  8361. * @returns a new observable
  8362. */
  8363. Observable.prototype.clone = function () {
  8364. var result = new Observable();
  8365. result._observers = this._observers.slice(0);
  8366. return result;
  8367. };
  8368. /**
  8369. * Does this observable handles observer registered with a given mask
  8370. * @param mask defines the mask to be tested
  8371. * @return whether or not one observer registered with the given mask is handeled
  8372. **/
  8373. Observable.prototype.hasSpecificMask = function (mask) {
  8374. if (mask === void 0) { mask = -1; }
  8375. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8376. var obs = _a[_i];
  8377. if (obs.mask & mask || obs.mask === mask) {
  8378. return true;
  8379. }
  8380. }
  8381. return false;
  8382. };
  8383. return Observable;
  8384. }());
  8385. BABYLON.Observable = Observable;
  8386. })(BABYLON || (BABYLON = {}));
  8387. //# sourceMappingURL=babylon.observable.js.map
  8388. var BABYLON;
  8389. (function (BABYLON) {
  8390. var SmartArray = /** @class */ (function () {
  8391. function SmartArray(capacity) {
  8392. this.length = 0;
  8393. this.data = new Array(capacity);
  8394. this._id = SmartArray._GlobalId++;
  8395. }
  8396. SmartArray.prototype.push = function (value) {
  8397. this.data[this.length++] = value;
  8398. if (this.length > this.data.length) {
  8399. this.data.length *= 2;
  8400. }
  8401. };
  8402. SmartArray.prototype.forEach = function (func) {
  8403. for (var index = 0; index < this.length; index++) {
  8404. func(this.data[index]);
  8405. }
  8406. };
  8407. SmartArray.prototype.sort = function (compareFn) {
  8408. this.data.sort(compareFn);
  8409. };
  8410. SmartArray.prototype.reset = function () {
  8411. this.length = 0;
  8412. };
  8413. SmartArray.prototype.dispose = function () {
  8414. this.reset();
  8415. if (this.data) {
  8416. this.data.length = 0;
  8417. this.data = [];
  8418. }
  8419. };
  8420. SmartArray.prototype.concat = function (array) {
  8421. if (array.length === 0) {
  8422. return;
  8423. }
  8424. if (this.length + array.length > this.data.length) {
  8425. this.data.length = (this.length + array.length) * 2;
  8426. }
  8427. for (var index = 0; index < array.length; index++) {
  8428. this.data[this.length++] = (array.data || array)[index];
  8429. }
  8430. };
  8431. SmartArray.prototype.indexOf = function (value) {
  8432. var position = this.data.indexOf(value);
  8433. if (position >= this.length) {
  8434. return -1;
  8435. }
  8436. return position;
  8437. };
  8438. SmartArray.prototype.contains = function (value) {
  8439. return this.data.indexOf(value) !== -1;
  8440. };
  8441. // Statics
  8442. SmartArray._GlobalId = 0;
  8443. return SmartArray;
  8444. }());
  8445. BABYLON.SmartArray = SmartArray;
  8446. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8447. __extends(SmartArrayNoDuplicate, _super);
  8448. function SmartArrayNoDuplicate() {
  8449. var _this = _super !== null && _super.apply(this, arguments) || this;
  8450. _this._duplicateId = 0;
  8451. return _this;
  8452. }
  8453. SmartArrayNoDuplicate.prototype.push = function (value) {
  8454. _super.prototype.push.call(this, value);
  8455. if (!value.__smartArrayFlags) {
  8456. value.__smartArrayFlags = {};
  8457. }
  8458. value.__smartArrayFlags[this._id] = this._duplicateId;
  8459. };
  8460. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8461. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8462. return false;
  8463. }
  8464. this.push(value);
  8465. return true;
  8466. };
  8467. SmartArrayNoDuplicate.prototype.reset = function () {
  8468. _super.prototype.reset.call(this);
  8469. this._duplicateId++;
  8470. };
  8471. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8472. if (array.length === 0) {
  8473. return;
  8474. }
  8475. if (this.length + array.length > this.data.length) {
  8476. this.data.length = (this.length + array.length) * 2;
  8477. }
  8478. for (var index = 0; index < array.length; index++) {
  8479. var item = (array.data || array)[index];
  8480. this.pushNoDuplicate(item);
  8481. }
  8482. };
  8483. return SmartArrayNoDuplicate;
  8484. }(SmartArray));
  8485. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8486. })(BABYLON || (BABYLON = {}));
  8487. //# sourceMappingURL=babylon.smartArray.js.map
  8488. var BABYLON;
  8489. (function (BABYLON) {
  8490. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8491. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8492. var LoadFileError = /** @class */ (function (_super) {
  8493. __extends(LoadFileError, _super);
  8494. function LoadFileError(message, request) {
  8495. var _this = _super.call(this, message) || this;
  8496. _this.request = request;
  8497. _this.name = "LoadFileError";
  8498. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8499. return _this;
  8500. }
  8501. // Polyfill for Object.setPrototypeOf if necessary.
  8502. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8503. return LoadFileError;
  8504. }(Error));
  8505. BABYLON.LoadFileError = LoadFileError;
  8506. var RetryStrategy = /** @class */ (function () {
  8507. function RetryStrategy() {
  8508. }
  8509. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8510. if (maxRetries === void 0) { maxRetries = 3; }
  8511. if (baseInterval === void 0) { baseInterval = 500; }
  8512. return function (url, request, retryIndex) {
  8513. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8514. return -1;
  8515. }
  8516. return Math.pow(2, retryIndex) * baseInterval;
  8517. };
  8518. };
  8519. return RetryStrategy;
  8520. }());
  8521. BABYLON.RetryStrategy = RetryStrategy;
  8522. // Screenshots
  8523. var screenshotCanvas;
  8524. var cloneValue = function (source, destinationObject) {
  8525. if (!source)
  8526. return null;
  8527. if (source instanceof BABYLON.Mesh) {
  8528. return null;
  8529. }
  8530. if (source instanceof BABYLON.SubMesh) {
  8531. return source.clone(destinationObject);
  8532. }
  8533. else if (source.clone) {
  8534. return source.clone();
  8535. }
  8536. return null;
  8537. };
  8538. var Tools = /** @class */ (function () {
  8539. function Tools() {
  8540. }
  8541. /**
  8542. * Interpolates between a and b via alpha
  8543. * @param a The lower value (returned when alpha = 0)
  8544. * @param b The upper value (returned when alpha = 1)
  8545. * @param alpha The interpolation-factor
  8546. * @return The mixed value
  8547. */
  8548. Tools.Mix = function (a, b, alpha) {
  8549. return a * (1 - alpha) + b * alpha;
  8550. };
  8551. Tools.Instantiate = function (className) {
  8552. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8553. return Tools.RegisteredExternalClasses[className];
  8554. }
  8555. var arr = className.split(".");
  8556. var fn = (window || this);
  8557. for (var i = 0, len = arr.length; i < len; i++) {
  8558. fn = fn[arr[i]];
  8559. }
  8560. if (typeof fn !== "function") {
  8561. return null;
  8562. }
  8563. return fn;
  8564. };
  8565. /**
  8566. * Provides a slice function that will work even on IE
  8567. * @param data defines the array to slice
  8568. * @param start defines the start of the data (optional)
  8569. * @param end defines the end of the data (optional)
  8570. * @returns the new sliced array
  8571. */
  8572. Tools.Slice = function (data, start, end) {
  8573. if (data.slice) {
  8574. return data.slice(start, end);
  8575. }
  8576. return Array.prototype.slice.call(data, start, end);
  8577. };
  8578. Tools.SetImmediate = function (action) {
  8579. if (window.setImmediate) {
  8580. window.setImmediate(action);
  8581. }
  8582. else {
  8583. setTimeout(action, 1);
  8584. }
  8585. };
  8586. Tools.IsExponentOfTwo = function (value) {
  8587. var count = 1;
  8588. do {
  8589. count *= 2;
  8590. } while (count < value);
  8591. return count === value;
  8592. };
  8593. /**
  8594. * Returns the nearest 32-bit single precision float representation of a Number
  8595. * @param value A Number. If the parameter is of a different type, it will get converted
  8596. * to a number or to NaN if it cannot be converted
  8597. * @returns number
  8598. */
  8599. Tools.FloatRound = function (value) {
  8600. if (Math.fround) {
  8601. return Math.fround(value);
  8602. }
  8603. return (Tools._tmpFloatArray[0] = value);
  8604. };
  8605. /**
  8606. * Find the next highest power of two.
  8607. * @param x Number to start search from.
  8608. * @return Next highest power of two.
  8609. */
  8610. Tools.CeilingPOT = function (x) {
  8611. x--;
  8612. x |= x >> 1;
  8613. x |= x >> 2;
  8614. x |= x >> 4;
  8615. x |= x >> 8;
  8616. x |= x >> 16;
  8617. x++;
  8618. return x;
  8619. };
  8620. /**
  8621. * Find the next lowest power of two.
  8622. * @param x Number to start search from.
  8623. * @return Next lowest power of two.
  8624. */
  8625. Tools.FloorPOT = function (x) {
  8626. x = x | (x >> 1);
  8627. x = x | (x >> 2);
  8628. x = x | (x >> 4);
  8629. x = x | (x >> 8);
  8630. x = x | (x >> 16);
  8631. return x - (x >> 1);
  8632. };
  8633. /**
  8634. * Find the nearest power of two.
  8635. * @param x Number to start search from.
  8636. * @return Next nearest power of two.
  8637. */
  8638. Tools.NearestPOT = function (x) {
  8639. var c = Tools.CeilingPOT(x);
  8640. var f = Tools.FloorPOT(x);
  8641. return (c - x) > (x - f) ? f : c;
  8642. };
  8643. Tools.GetExponentOfTwo = function (value, max, mode) {
  8644. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8645. var pot;
  8646. switch (mode) {
  8647. case BABYLON.Engine.SCALEMODE_FLOOR:
  8648. pot = Tools.FloorPOT(value);
  8649. break;
  8650. case BABYLON.Engine.SCALEMODE_NEAREST:
  8651. pot = Tools.NearestPOT(value);
  8652. break;
  8653. case BABYLON.Engine.SCALEMODE_CEILING:
  8654. default:
  8655. pot = Tools.CeilingPOT(value);
  8656. break;
  8657. }
  8658. return Math.min(pot, max);
  8659. };
  8660. Tools.GetFilename = function (path) {
  8661. var index = path.lastIndexOf("/");
  8662. if (index < 0)
  8663. return path;
  8664. return path.substring(index + 1);
  8665. };
  8666. /**
  8667. * Extracts the "folder" part of a path (everything before the filename).
  8668. * @param uri The URI to extract the info from
  8669. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8670. * @returns The "folder" part of the path
  8671. */
  8672. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8673. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8674. var index = uri.lastIndexOf("/");
  8675. if (index < 0) {
  8676. if (returnUnchangedIfNoSlash) {
  8677. return uri;
  8678. }
  8679. return "";
  8680. }
  8681. return uri.substring(0, index + 1);
  8682. };
  8683. Tools.GetDOMTextContent = function (element) {
  8684. var result = "";
  8685. var child = element.firstChild;
  8686. while (child) {
  8687. if (child.nodeType === 3) {
  8688. result += child.textContent;
  8689. }
  8690. child = child.nextSibling;
  8691. }
  8692. return result;
  8693. };
  8694. Tools.ToDegrees = function (angle) {
  8695. return angle * 180 / Math.PI;
  8696. };
  8697. Tools.ToRadians = function (angle) {
  8698. return angle * Math.PI / 180;
  8699. };
  8700. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8701. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8702. var output = "";
  8703. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8704. var i = 0;
  8705. var bytes = new Uint8Array(buffer);
  8706. while (i < bytes.length) {
  8707. chr1 = bytes[i++];
  8708. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8709. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8710. enc1 = chr1 >> 2;
  8711. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8712. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8713. enc4 = chr3 & 63;
  8714. if (isNaN(chr2)) {
  8715. enc3 = enc4 = 64;
  8716. }
  8717. else if (isNaN(chr3)) {
  8718. enc4 = 64;
  8719. }
  8720. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8721. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8722. }
  8723. return "data:image/png;base64," + output;
  8724. };
  8725. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8726. if (bias === void 0) { bias = null; }
  8727. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8728. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8729. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8730. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8731. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8732. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8733. }
  8734. if (bias) {
  8735. minimum.x -= minimum.x * bias.x + bias.y;
  8736. minimum.y -= minimum.y * bias.x + bias.y;
  8737. minimum.z -= minimum.z * bias.x + bias.y;
  8738. maximum.x += maximum.x * bias.x + bias.y;
  8739. maximum.y += maximum.y * bias.x + bias.y;
  8740. maximum.z += maximum.z * bias.x + bias.y;
  8741. }
  8742. return {
  8743. minimum: minimum,
  8744. maximum: maximum
  8745. };
  8746. };
  8747. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8748. if (bias === void 0) { bias = null; }
  8749. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8750. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8751. if (!stride) {
  8752. stride = 3;
  8753. }
  8754. for (var index = start; index < start + count; index++) {
  8755. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8756. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8757. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8758. }
  8759. if (bias) {
  8760. minimum.x -= minimum.x * bias.x + bias.y;
  8761. minimum.y -= minimum.y * bias.x + bias.y;
  8762. minimum.z -= minimum.z * bias.x + bias.y;
  8763. maximum.x += maximum.x * bias.x + bias.y;
  8764. maximum.y += maximum.y * bias.x + bias.y;
  8765. maximum.z += maximum.z * bias.x + bias.y;
  8766. }
  8767. return {
  8768. minimum: minimum,
  8769. maximum: maximum
  8770. };
  8771. };
  8772. Tools.Vector2ArrayFeeder = function (array) {
  8773. return function (index) {
  8774. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8775. var length = isFloatArray ? array.length / 2 : array.length;
  8776. if (index >= length) {
  8777. return null;
  8778. }
  8779. if (isFloatArray) {
  8780. var fa = array;
  8781. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8782. }
  8783. var a = array;
  8784. return a[index];
  8785. };
  8786. };
  8787. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8788. if (bias === void 0) { bias = null; }
  8789. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8790. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8791. var i = 0;
  8792. var cur = feeder(i++);
  8793. while (cur) {
  8794. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8795. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8796. cur = feeder(i++);
  8797. }
  8798. if (bias) {
  8799. minimum.x -= minimum.x * bias.x + bias.y;
  8800. minimum.y -= minimum.y * bias.x + bias.y;
  8801. maximum.x += maximum.x * bias.x + bias.y;
  8802. maximum.y += maximum.y * bias.x + bias.y;
  8803. }
  8804. return {
  8805. minimum: minimum,
  8806. maximum: maximum
  8807. };
  8808. };
  8809. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8810. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8811. return null;
  8812. return Array.isArray(obj) ? obj : [obj];
  8813. };
  8814. // Misc.
  8815. Tools.GetPointerPrefix = function () {
  8816. var eventPrefix = "pointer";
  8817. // Check if pointer events are supported
  8818. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8819. eventPrefix = "mouse";
  8820. }
  8821. return eventPrefix;
  8822. };
  8823. /**
  8824. * @param func - the function to be called
  8825. * @param requester - the object that will request the next frame. Falls back to window.
  8826. */
  8827. Tools.QueueNewFrame = function (func, requester) {
  8828. if (!Tools.IsWindowObjectExist()) {
  8829. return setTimeout(func, 16);
  8830. }
  8831. if (!requester) {
  8832. requester = window;
  8833. }
  8834. if (requester.requestAnimationFrame) {
  8835. return requester.requestAnimationFrame(func);
  8836. }
  8837. else if (requester.msRequestAnimationFrame) {
  8838. return requester.msRequestAnimationFrame(func);
  8839. }
  8840. else if (requester.webkitRequestAnimationFrame) {
  8841. return requester.webkitRequestAnimationFrame(func);
  8842. }
  8843. else if (requester.mozRequestAnimationFrame) {
  8844. return requester.mozRequestAnimationFrame(func);
  8845. }
  8846. else if (requester.oRequestAnimationFrame) {
  8847. return requester.oRequestAnimationFrame(func);
  8848. }
  8849. else {
  8850. return window.setTimeout(func, 16);
  8851. }
  8852. };
  8853. Tools.RequestFullscreen = function (element) {
  8854. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8855. if (!requestFunction)
  8856. return;
  8857. requestFunction.call(element);
  8858. };
  8859. Tools.ExitFullscreen = function () {
  8860. if (document.exitFullscreen) {
  8861. document.exitFullscreen();
  8862. }
  8863. else if (document.mozCancelFullScreen) {
  8864. document.mozCancelFullScreen();
  8865. }
  8866. else if (document.webkitCancelFullScreen) {
  8867. document.webkitCancelFullScreen();
  8868. }
  8869. else if (document.msCancelFullScreen) {
  8870. document.msCancelFullScreen();
  8871. }
  8872. };
  8873. Tools.SetCorsBehavior = function (url, element) {
  8874. if (url && url.indexOf("data:") === 0) {
  8875. return;
  8876. }
  8877. if (Tools.CorsBehavior) {
  8878. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8879. element.crossOrigin = Tools.CorsBehavior;
  8880. }
  8881. else {
  8882. var result = Tools.CorsBehavior(url);
  8883. if (result) {
  8884. element.crossOrigin = result;
  8885. }
  8886. }
  8887. }
  8888. };
  8889. // External files
  8890. Tools.CleanUrl = function (url) {
  8891. url = url.replace(/#/mg, "%23");
  8892. return url;
  8893. };
  8894. /**
  8895. * Loads an image as an HTMLImageElement.
  8896. * @param input url string, ArrayBuffer, or Blob to load
  8897. * @param onLoad callback called when the image successfully loads
  8898. * @param onError callback called when the image fails to load
  8899. * @param database database for caching
  8900. * @returns the HTMLImageElement of the loaded image
  8901. */
  8902. Tools.LoadImage = function (input, onLoad, onError, database) {
  8903. var url;
  8904. var usingObjectURL = false;
  8905. if (input instanceof ArrayBuffer) {
  8906. url = URL.createObjectURL(new Blob([input]));
  8907. usingObjectURL = true;
  8908. }
  8909. else if (input instanceof Blob) {
  8910. url = URL.createObjectURL(input);
  8911. usingObjectURL = true;
  8912. }
  8913. else {
  8914. url = Tools.CleanUrl(input);
  8915. url = Tools.PreprocessUrl(input);
  8916. }
  8917. var img = new Image();
  8918. Tools.SetCorsBehavior(url, img);
  8919. var loadHandler = function () {
  8920. if (usingObjectURL && img.src) {
  8921. URL.revokeObjectURL(img.src);
  8922. }
  8923. img.removeEventListener("load", loadHandler);
  8924. img.removeEventListener("error", errorHandler);
  8925. onLoad(img);
  8926. };
  8927. var errorHandler = function (err) {
  8928. if (usingObjectURL && img.src) {
  8929. URL.revokeObjectURL(img.src);
  8930. }
  8931. img.removeEventListener("load", loadHandler);
  8932. img.removeEventListener("error", errorHandler);
  8933. Tools.Error("Error while trying to load image: " + input);
  8934. if (onError) {
  8935. onError("Error while trying to load image: " + input, err);
  8936. }
  8937. };
  8938. img.addEventListener("load", loadHandler);
  8939. img.addEventListener("error", errorHandler);
  8940. var noIndexedDB = function () {
  8941. img.src = url;
  8942. };
  8943. var loadFromIndexedDB = function () {
  8944. if (database) {
  8945. database.loadImageFromDB(url, img);
  8946. }
  8947. };
  8948. //ANY database to do!
  8949. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8950. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8951. }
  8952. else {
  8953. if (url.indexOf("file:") !== -1) {
  8954. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8955. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8956. try {
  8957. var blobURL;
  8958. try {
  8959. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8960. }
  8961. catch (ex) {
  8962. // Chrome doesn't support oneTimeOnly parameter
  8963. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8964. }
  8965. img.src = blobURL;
  8966. usingObjectURL = true;
  8967. }
  8968. catch (e) {
  8969. img.src = "";
  8970. }
  8971. return img;
  8972. }
  8973. }
  8974. noIndexedDB();
  8975. }
  8976. return img;
  8977. };
  8978. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8979. url = Tools.CleanUrl(url);
  8980. url = Tools.PreprocessUrl(url);
  8981. // If file and file input are set
  8982. if (url.indexOf("file:") !== -1) {
  8983. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8984. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8985. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8986. }
  8987. }
  8988. var loadUrl = Tools.BaseUrl + url;
  8989. var aborted = false;
  8990. var fileRequest = {
  8991. onCompleteObservable: new BABYLON.Observable(),
  8992. abort: function () { return aborted = true; },
  8993. };
  8994. var requestFile = function () {
  8995. var request = new XMLHttpRequest();
  8996. var retryHandle = null;
  8997. fileRequest.abort = function () {
  8998. aborted = true;
  8999. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9000. request.abort();
  9001. }
  9002. if (retryHandle !== null) {
  9003. clearTimeout(retryHandle);
  9004. retryHandle = null;
  9005. }
  9006. };
  9007. var retryLoop = function (retryIndex) {
  9008. request.open('GET', loadUrl, true);
  9009. if (useArrayBuffer) {
  9010. request.responseType = "arraybuffer";
  9011. }
  9012. if (onProgress) {
  9013. request.addEventListener("progress", onProgress);
  9014. }
  9015. var onLoadEnd = function () {
  9016. request.removeEventListener("loadend", onLoadEnd);
  9017. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9018. fileRequest.onCompleteObservable.clear();
  9019. };
  9020. request.addEventListener("loadend", onLoadEnd);
  9021. var onReadyStateChange = function () {
  9022. if (aborted) {
  9023. return;
  9024. }
  9025. // In case of undefined state in some browsers.
  9026. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9027. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9028. request.removeEventListener("readystatechange", onReadyStateChange);
  9029. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9030. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9031. return;
  9032. }
  9033. var retryStrategy = Tools.DefaultRetryStrategy;
  9034. if (retryStrategy) {
  9035. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9036. if (waitTime !== -1) {
  9037. // Prevent the request from completing for retry.
  9038. request.removeEventListener("loadend", onLoadEnd);
  9039. request = new XMLHttpRequest();
  9040. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9041. return;
  9042. }
  9043. }
  9044. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9045. if (onError) {
  9046. onError(request, e);
  9047. }
  9048. else {
  9049. throw e;
  9050. }
  9051. }
  9052. };
  9053. request.addEventListener("readystatechange", onReadyStateChange);
  9054. request.send();
  9055. };
  9056. retryLoop(0);
  9057. };
  9058. // Caching all files
  9059. if (database && database.enableSceneOffline) {
  9060. var noIndexedDB_1 = function () {
  9061. if (!aborted) {
  9062. requestFile();
  9063. }
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. // TODO: database needs to support aborting and should return a IFileRequest
  9067. if (aborted) {
  9068. return;
  9069. }
  9070. if (database) {
  9071. database.loadFileFromDB(url, function (data) {
  9072. if (!aborted) {
  9073. onSuccess(data);
  9074. }
  9075. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9076. }, onProgress ? function (event) {
  9077. if (!aborted) {
  9078. onProgress(event);
  9079. }
  9080. } : undefined, noIndexedDB_1, useArrayBuffer);
  9081. }
  9082. };
  9083. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9084. }
  9085. else {
  9086. requestFile();
  9087. }
  9088. return fileRequest;
  9089. };
  9090. /**
  9091. * Load a script (identified by an url). When the url returns, the
  9092. * content of this file is added into a new script element, attached to the DOM (body element)
  9093. */
  9094. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9095. var head = document.getElementsByTagName('head')[0];
  9096. var script = document.createElement('script');
  9097. script.type = 'text/javascript';
  9098. script.src = scriptUrl;
  9099. script.onload = function () {
  9100. if (onSuccess) {
  9101. onSuccess();
  9102. }
  9103. };
  9104. script.onerror = function (e) {
  9105. if (onError) {
  9106. onError("Unable to load script '" + scriptUrl + "'", e);
  9107. }
  9108. };
  9109. head.appendChild(script);
  9110. };
  9111. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9112. var reader = new FileReader();
  9113. var request = {
  9114. onCompleteObservable: new BABYLON.Observable(),
  9115. abort: function () { return reader.abort(); },
  9116. };
  9117. reader.onloadend = function (e) {
  9118. request.onCompleteObservable.notifyObservers(request);
  9119. };
  9120. reader.onload = function (e) {
  9121. //target doesn't have result from ts 1.3
  9122. callback(e.target['result']);
  9123. };
  9124. reader.onprogress = progressCallback;
  9125. reader.readAsDataURL(fileToLoad);
  9126. return request;
  9127. };
  9128. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9129. var reader = new FileReader();
  9130. var request = {
  9131. onCompleteObservable: new BABYLON.Observable(),
  9132. abort: function () { return reader.abort(); },
  9133. };
  9134. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9135. reader.onerror = function (e) {
  9136. Tools.Log("Error while reading file: " + fileToLoad.name);
  9137. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9138. };
  9139. reader.onload = function (e) {
  9140. //target doesn't have result from ts 1.3
  9141. callback(e.target['result']);
  9142. };
  9143. if (progressCallBack) {
  9144. reader.onprogress = progressCallBack;
  9145. }
  9146. if (!useArrayBuffer) {
  9147. // Asynchronous read
  9148. reader.readAsText(fileToLoad);
  9149. }
  9150. else {
  9151. reader.readAsArrayBuffer(fileToLoad);
  9152. }
  9153. return request;
  9154. };
  9155. //returns a downloadable url to a file content.
  9156. Tools.FileAsURL = function (content) {
  9157. var fileBlob = new Blob([content]);
  9158. var url = window.URL || window.webkitURL;
  9159. var link = url.createObjectURL(fileBlob);
  9160. return link;
  9161. };
  9162. // Misc.
  9163. Tools.Format = function (value, decimals) {
  9164. if (decimals === void 0) { decimals = 2; }
  9165. return value.toFixed(decimals);
  9166. };
  9167. Tools.CheckExtends = function (v, min, max) {
  9168. if (v.x < min.x)
  9169. min.x = v.x;
  9170. if (v.y < min.y)
  9171. min.y = v.y;
  9172. if (v.z < min.z)
  9173. min.z = v.z;
  9174. if (v.x > max.x)
  9175. max.x = v.x;
  9176. if (v.y > max.y)
  9177. max.y = v.y;
  9178. if (v.z > max.z)
  9179. max.z = v.z;
  9180. };
  9181. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9182. for (var prop in source) {
  9183. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9184. continue;
  9185. }
  9186. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9187. continue;
  9188. }
  9189. var sourceValue = source[prop];
  9190. var typeOfSourceValue = typeof sourceValue;
  9191. if (typeOfSourceValue === "function") {
  9192. continue;
  9193. }
  9194. try {
  9195. if (typeOfSourceValue === "object") {
  9196. if (sourceValue instanceof Array) {
  9197. destination[prop] = [];
  9198. if (sourceValue.length > 0) {
  9199. if (typeof sourceValue[0] == "object") {
  9200. for (var index = 0; index < sourceValue.length; index++) {
  9201. var clonedValue = cloneValue(sourceValue[index], destination);
  9202. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9203. destination[prop].push(clonedValue);
  9204. }
  9205. }
  9206. }
  9207. else {
  9208. destination[prop] = sourceValue.slice(0);
  9209. }
  9210. }
  9211. }
  9212. else {
  9213. destination[prop] = cloneValue(sourceValue, destination);
  9214. }
  9215. }
  9216. else {
  9217. destination[prop] = sourceValue;
  9218. }
  9219. }
  9220. catch (e) {
  9221. // Just ignore error (it could be because of a read-only property)
  9222. }
  9223. }
  9224. };
  9225. Tools.IsEmpty = function (obj) {
  9226. for (var i in obj) {
  9227. if (obj.hasOwnProperty(i)) {
  9228. return false;
  9229. }
  9230. }
  9231. return true;
  9232. };
  9233. Tools.RegisterTopRootEvents = function (events) {
  9234. for (var index = 0; index < events.length; index++) {
  9235. var event = events[index];
  9236. window.addEventListener(event.name, event.handler, false);
  9237. try {
  9238. if (window.parent) {
  9239. window.parent.addEventListener(event.name, event.handler, false);
  9240. }
  9241. }
  9242. catch (e) {
  9243. // Silently fails...
  9244. }
  9245. }
  9246. };
  9247. Tools.UnregisterTopRootEvents = function (events) {
  9248. for (var index = 0; index < events.length; index++) {
  9249. var event = events[index];
  9250. window.removeEventListener(event.name, event.handler);
  9251. try {
  9252. if (window.parent) {
  9253. window.parent.removeEventListener(event.name, event.handler);
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Silently fails...
  9258. }
  9259. }
  9260. };
  9261. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9262. if (mimeType === void 0) { mimeType = "image/png"; }
  9263. // Read the contents of the framebuffer
  9264. var numberOfChannelsByLine = width * 4;
  9265. var halfHeight = height / 2;
  9266. //Reading datas from WebGL
  9267. var data = engine.readPixels(0, 0, width, height);
  9268. //To flip image on Y axis.
  9269. for (var i = 0; i < halfHeight; i++) {
  9270. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9271. var currentCell = j + i * numberOfChannelsByLine;
  9272. var targetLine = height - i - 1;
  9273. var targetCell = j + targetLine * numberOfChannelsByLine;
  9274. var temp = data[currentCell];
  9275. data[currentCell] = data[targetCell];
  9276. data[targetCell] = temp;
  9277. }
  9278. }
  9279. // Create a 2D canvas to store the result
  9280. if (!screenshotCanvas) {
  9281. screenshotCanvas = document.createElement('canvas');
  9282. }
  9283. screenshotCanvas.width = width;
  9284. screenshotCanvas.height = height;
  9285. var context = screenshotCanvas.getContext('2d');
  9286. if (context) {
  9287. // Copy the pixels to a 2D canvas
  9288. var imageData = context.createImageData(width, height);
  9289. var castData = (imageData.data);
  9290. castData.set(data);
  9291. context.putImageData(imageData, 0, 0);
  9292. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9293. }
  9294. };
  9295. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9296. if (mimeType === void 0) { mimeType = "image/png"; }
  9297. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9298. if (successCallback) {
  9299. successCallback(base64Image);
  9300. }
  9301. else {
  9302. // We need HTMLCanvasElement.toBlob for HD screenshots
  9303. if (!screenshotCanvas.toBlob) {
  9304. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9305. screenshotCanvas.toBlob = function (callback, type, quality) {
  9306. var _this = this;
  9307. setTimeout(function () {
  9308. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9309. for (var i = 0; i < len; i++) {
  9310. arr[i] = binStr.charCodeAt(i);
  9311. }
  9312. callback(new Blob([arr], { type: type || 'image/png' }));
  9313. });
  9314. };
  9315. }
  9316. screenshotCanvas.toBlob(function (blob) {
  9317. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9318. if (("download" in document.createElement("a"))) {
  9319. if (!fileName) {
  9320. var date = new Date();
  9321. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9322. fileName = "screenshot_" + stringDate + ".png";
  9323. }
  9324. Tools.Download(blob, fileName);
  9325. }
  9326. else {
  9327. var url = URL.createObjectURL(blob);
  9328. var newWindow = window.open("");
  9329. if (!newWindow)
  9330. return;
  9331. var img = newWindow.document.createElement("img");
  9332. img.onload = function () {
  9333. // no longer need to read the blob so it's revoked
  9334. URL.revokeObjectURL(url);
  9335. };
  9336. img.src = url;
  9337. newWindow.document.body.appendChild(img);
  9338. }
  9339. });
  9340. }
  9341. };
  9342. /**
  9343. * Downloads a blob in the browser
  9344. * @param blob defines the blob to download
  9345. * @param fileName defines the name of the downloaded file
  9346. */
  9347. Tools.Download = function (blob, fileName) {
  9348. var url = window.URL.createObjectURL(blob);
  9349. var a = document.createElement("a");
  9350. document.body.appendChild(a);
  9351. a.style.display = "none";
  9352. a.href = url;
  9353. a.download = fileName;
  9354. a.addEventListener("click", function () {
  9355. if (a.parentElement) {
  9356. a.parentElement.removeChild(a);
  9357. }
  9358. });
  9359. a.click();
  9360. window.URL.revokeObjectURL(url);
  9361. };
  9362. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9363. if (mimeType === void 0) { mimeType = "image/png"; }
  9364. var width;
  9365. var height;
  9366. // If a precision value is specified
  9367. if (size.precision) {
  9368. width = Math.round(engine.getRenderWidth() * size.precision);
  9369. height = Math.round(width / engine.getAspectRatio(camera));
  9370. }
  9371. else if (size.width && size.height) {
  9372. width = size.width;
  9373. height = size.height;
  9374. }
  9375. //If passing only width, computing height to keep display canvas ratio.
  9376. else if (size.width && !size.height) {
  9377. width = size.width;
  9378. height = Math.round(width / engine.getAspectRatio(camera));
  9379. }
  9380. //If passing only height, computing width to keep display canvas ratio.
  9381. else if (size.height && !size.width) {
  9382. height = size.height;
  9383. width = Math.round(height * engine.getAspectRatio(camera));
  9384. }
  9385. //Assuming here that "size" parameter is a number
  9386. else if (!isNaN(size)) {
  9387. height = size;
  9388. width = size;
  9389. }
  9390. else {
  9391. Tools.Error("Invalid 'size' parameter !");
  9392. return;
  9393. }
  9394. if (!screenshotCanvas) {
  9395. screenshotCanvas = document.createElement('canvas');
  9396. }
  9397. screenshotCanvas.width = width;
  9398. screenshotCanvas.height = height;
  9399. var renderContext = screenshotCanvas.getContext("2d");
  9400. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9401. var newWidth = width;
  9402. var newHeight = newWidth / ratio;
  9403. if (newHeight > height) {
  9404. newHeight = height;
  9405. newWidth = newHeight * ratio;
  9406. }
  9407. var offsetX = Math.max(0, width - newWidth) / 2;
  9408. var offsetY = Math.max(0, height - newHeight) / 2;
  9409. var renderingCanvas = engine.getRenderingCanvas();
  9410. if (renderContext && renderingCanvas) {
  9411. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9412. }
  9413. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9414. };
  9415. /**
  9416. * Generates an image screenshot from the specified camera.
  9417. *
  9418. * @param engine The engine to use for rendering
  9419. * @param camera The camera to use for rendering
  9420. * @param size This parameter can be set to a single number or to an object with the
  9421. * following (optional) properties: precision, width, height. If a single number is passed,
  9422. * it will be used for both width and height. If an object is passed, the screenshot size
  9423. * will be derived from the parameters. The precision property is a multiplier allowing
  9424. * rendering at a higher or lower resolution.
  9425. * @param successCallback The callback receives a single parameter which contains the
  9426. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9427. * src parameter of an <img> to display it.
  9428. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9429. * Check your browser for supported MIME types.
  9430. * @param samples Texture samples (default: 1)
  9431. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9432. * @param fileName A name for for the downloaded file.
  9433. * @constructor
  9434. */
  9435. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9436. if (mimeType === void 0) { mimeType = "image/png"; }
  9437. if (samples === void 0) { samples = 1; }
  9438. if (antialiasing === void 0) { antialiasing = false; }
  9439. var width;
  9440. var height;
  9441. //If a precision value is specified
  9442. if (size.precision) {
  9443. width = Math.round(engine.getRenderWidth() * size.precision);
  9444. height = Math.round(width / engine.getAspectRatio(camera));
  9445. size = { width: width, height: height };
  9446. }
  9447. else if (size.width && size.height) {
  9448. width = size.width;
  9449. height = size.height;
  9450. }
  9451. //If passing only width, computing height to keep display canvas ratio.
  9452. else if (size.width && !size.height) {
  9453. width = size.width;
  9454. height = Math.round(width / engine.getAspectRatio(camera));
  9455. size = { width: width, height: height };
  9456. }
  9457. //If passing only height, computing width to keep display canvas ratio.
  9458. else if (size.height && !size.width) {
  9459. height = size.height;
  9460. width = Math.round(height * engine.getAspectRatio(camera));
  9461. size = { width: width, height: height };
  9462. }
  9463. //Assuming here that "size" parameter is a number
  9464. else if (!isNaN(size)) {
  9465. height = size;
  9466. width = size;
  9467. }
  9468. else {
  9469. Tools.Error("Invalid 'size' parameter !");
  9470. return;
  9471. }
  9472. var scene = camera.getScene();
  9473. var previousCamera = null;
  9474. if (scene.activeCamera !== camera) {
  9475. previousCamera = scene.activeCamera;
  9476. scene.activeCamera = camera;
  9477. }
  9478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9480. texture.renderList = null;
  9481. texture.samples = samples;
  9482. if (antialiasing) {
  9483. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9484. }
  9485. texture.onAfterRenderObservable.add(function () {
  9486. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9487. });
  9488. scene.incrementRenderId();
  9489. scene.resetCachedMaterial();
  9490. texture.render(true);
  9491. texture.dispose();
  9492. if (previousCamera) {
  9493. scene.activeCamera = previousCamera;
  9494. }
  9495. camera.getProjectionMatrix(true); // Force cache refresh;
  9496. };
  9497. // XHR response validator for local file scenario
  9498. Tools.ValidateXHRData = function (xhr, dataType) {
  9499. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9500. if (dataType === void 0) { dataType = 7; }
  9501. try {
  9502. if (dataType & 1) {
  9503. if (xhr.responseText && xhr.responseText.length > 0) {
  9504. return true;
  9505. }
  9506. else if (dataType === 1) {
  9507. return false;
  9508. }
  9509. }
  9510. if (dataType & 2) {
  9511. // Check header width and height since there is no "TGA" magic number
  9512. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9513. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9514. return true;
  9515. }
  9516. else if (dataType === 2) {
  9517. return false;
  9518. }
  9519. }
  9520. if (dataType & 4) {
  9521. // Check for the "DDS" magic number
  9522. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9523. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9524. return true;
  9525. }
  9526. else {
  9527. return false;
  9528. }
  9529. }
  9530. }
  9531. catch (e) {
  9532. // Global protection
  9533. }
  9534. return false;
  9535. };
  9536. /**
  9537. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9538. * Be aware Math.random() could cause collisions, but:
  9539. * "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"
  9540. */
  9541. Tools.RandomId = function () {
  9542. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9543. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9544. return v.toString(16);
  9545. });
  9546. };
  9547. /**
  9548. * Test if the given uri is a base64 string.
  9549. * @param uri The uri to test
  9550. * @return True if the uri is a base64 string or false otherwise.
  9551. */
  9552. Tools.IsBase64 = function (uri) {
  9553. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9554. };
  9555. /**
  9556. * Decode the given base64 uri.
  9557. * @param uri The uri to decode
  9558. * @return The decoded base64 data.
  9559. */
  9560. Tools.DecodeBase64 = function (uri) {
  9561. var decodedString = atob(uri.split(",")[1]);
  9562. var bufferLength = decodedString.length;
  9563. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9564. for (var i = 0; i < bufferLength; i++) {
  9565. bufferView[i] = decodedString.charCodeAt(i);
  9566. }
  9567. return bufferView.buffer;
  9568. };
  9569. Object.defineProperty(Tools, "NoneLogLevel", {
  9570. get: function () {
  9571. return Tools._NoneLogLevel;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Tools, "MessageLogLevel", {
  9577. get: function () {
  9578. return Tools._MessageLogLevel;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(Tools, "WarningLogLevel", {
  9584. get: function () {
  9585. return Tools._WarningLogLevel;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(Tools, "ErrorLogLevel", {
  9591. get: function () {
  9592. return Tools._ErrorLogLevel;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(Tools, "AllLogLevel", {
  9598. get: function () {
  9599. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Tools._AddLogEntry = function (entry) {
  9605. Tools._LogCache = entry + Tools._LogCache;
  9606. if (Tools.OnNewCacheEntry) {
  9607. Tools.OnNewCacheEntry(entry);
  9608. }
  9609. };
  9610. Tools._FormatMessage = function (message) {
  9611. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9612. var date = new Date();
  9613. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9614. };
  9615. Tools._LogDisabled = function (message) {
  9616. // nothing to do
  9617. };
  9618. Tools._LogEnabled = function (message) {
  9619. var formattedMessage = Tools._FormatMessage(message);
  9620. console.log("BJS - " + formattedMessage);
  9621. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9622. Tools._AddLogEntry(entry);
  9623. };
  9624. Tools._WarnDisabled = function (message) {
  9625. // nothing to do
  9626. };
  9627. Tools._WarnEnabled = function (message) {
  9628. var formattedMessage = Tools._FormatMessage(message);
  9629. console.warn("BJS - " + formattedMessage);
  9630. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9631. Tools._AddLogEntry(entry);
  9632. };
  9633. Tools._ErrorDisabled = function (message) {
  9634. // nothing to do
  9635. };
  9636. Tools._ErrorEnabled = function (message) {
  9637. Tools.errorsCount++;
  9638. var formattedMessage = Tools._FormatMessage(message);
  9639. console.error("BJS - " + formattedMessage);
  9640. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9641. Tools._AddLogEntry(entry);
  9642. };
  9643. Object.defineProperty(Tools, "LogCache", {
  9644. get: function () {
  9645. return Tools._LogCache;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Tools.ClearLogCache = function () {
  9651. Tools._LogCache = "";
  9652. Tools.errorsCount = 0;
  9653. };
  9654. Object.defineProperty(Tools, "LogLevels", {
  9655. set: function (level) {
  9656. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9657. Tools.Log = Tools._LogEnabled;
  9658. }
  9659. else {
  9660. Tools.Log = Tools._LogDisabled;
  9661. }
  9662. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9663. Tools.Warn = Tools._WarnEnabled;
  9664. }
  9665. else {
  9666. Tools.Warn = Tools._WarnDisabled;
  9667. }
  9668. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9669. Tools.Error = Tools._ErrorEnabled;
  9670. }
  9671. else {
  9672. Tools.Error = Tools._ErrorDisabled;
  9673. }
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Tools.IsWindowObjectExist = function () {
  9679. return (typeof window) !== "undefined";
  9680. };
  9681. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9682. get: function () {
  9683. return Tools._PerformanceNoneLogLevel;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9689. get: function () {
  9690. return Tools._PerformanceUserMarkLogLevel;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9696. get: function () {
  9697. return Tools._PerformanceConsoleLogLevel;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9703. set: function (level) {
  9704. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9705. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9706. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9707. return;
  9708. }
  9709. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9710. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9711. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9712. return;
  9713. }
  9714. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9715. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9721. };
  9722. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9723. };
  9724. Tools._StartUserMark = function (counterName, condition) {
  9725. if (condition === void 0) { condition = true; }
  9726. if (!Tools._performance) {
  9727. if (!Tools.IsWindowObjectExist()) {
  9728. return;
  9729. }
  9730. Tools._performance = window.performance;
  9731. }
  9732. if (!condition || !Tools._performance.mark) {
  9733. return;
  9734. }
  9735. Tools._performance.mark(counterName + "-Begin");
  9736. };
  9737. Tools._EndUserMark = function (counterName, condition) {
  9738. if (condition === void 0) { condition = true; }
  9739. if (!condition || !Tools._performance.mark) {
  9740. return;
  9741. }
  9742. Tools._performance.mark(counterName + "-End");
  9743. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9744. };
  9745. Tools._StartPerformanceConsole = function (counterName, condition) {
  9746. if (condition === void 0) { condition = true; }
  9747. if (!condition) {
  9748. return;
  9749. }
  9750. Tools._StartUserMark(counterName, condition);
  9751. if (console.time) {
  9752. console.time(counterName);
  9753. }
  9754. };
  9755. Tools._EndPerformanceConsole = function (counterName, condition) {
  9756. if (condition === void 0) { condition = true; }
  9757. if (!condition) {
  9758. return;
  9759. }
  9760. Tools._EndUserMark(counterName, condition);
  9761. if (console.time) {
  9762. console.timeEnd(counterName);
  9763. }
  9764. };
  9765. Object.defineProperty(Tools, "Now", {
  9766. get: function () {
  9767. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9768. return window.performance.now();
  9769. }
  9770. return Date.now();
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. /**
  9776. * This method will return the name of the class used to create the instance of the given object.
  9777. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9778. * @param object the object to get the class name from
  9779. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9780. */
  9781. Tools.GetClassName = function (object, isType) {
  9782. if (isType === void 0) { isType = false; }
  9783. var name = null;
  9784. if (!isType && object.getClassName) {
  9785. name = object.getClassName();
  9786. }
  9787. else {
  9788. if (object instanceof Object) {
  9789. var classObj = isType ? object : Object.getPrototypeOf(object);
  9790. name = classObj.constructor["__bjsclassName__"];
  9791. }
  9792. if (!name) {
  9793. name = typeof object;
  9794. }
  9795. }
  9796. return name;
  9797. };
  9798. Tools.First = function (array, predicate) {
  9799. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9800. var el = array_1[_i];
  9801. if (predicate(el)) {
  9802. return el;
  9803. }
  9804. }
  9805. return null;
  9806. };
  9807. /**
  9808. * This method will return the name of the full name of the class, including its owning module (if any).
  9809. * 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).
  9810. * @param object the object to get the class name from
  9811. * @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.
  9812. */
  9813. Tools.getFullClassName = function (object, isType) {
  9814. if (isType === void 0) { isType = false; }
  9815. var className = null;
  9816. var moduleName = null;
  9817. if (!isType && object.getClassName) {
  9818. className = object.getClassName();
  9819. }
  9820. else {
  9821. if (object instanceof Object) {
  9822. var classObj = isType ? object : Object.getPrototypeOf(object);
  9823. className = classObj.constructor["__bjsclassName__"];
  9824. moduleName = classObj.constructor["__bjsmoduleName__"];
  9825. }
  9826. if (!className) {
  9827. className = typeof object;
  9828. }
  9829. }
  9830. if (!className) {
  9831. return null;
  9832. }
  9833. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9834. };
  9835. /**
  9836. * 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.
  9837. * @param array
  9838. */
  9839. Tools.arrayOrStringFeeder = function (array) {
  9840. return function (index) {
  9841. if (index >= array.length) {
  9842. return null;
  9843. }
  9844. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9845. if (val && val.getHashCode) {
  9846. val = val.getHashCode();
  9847. }
  9848. if (typeof val === "string") {
  9849. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9850. }
  9851. return val;
  9852. };
  9853. };
  9854. /**
  9855. * Compute the hashCode of a stream of number
  9856. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9857. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9858. * @return the hash code computed
  9859. */
  9860. Tools.hashCodeFromStream = function (feeder) {
  9861. // Based from here: http://stackoverflow.com/a/7616484/802124
  9862. var hash = 0;
  9863. var index = 0;
  9864. var chr = feeder(index++);
  9865. while (chr != null) {
  9866. hash = ((hash << 5) - hash) + chr;
  9867. hash |= 0; // Convert to 32bit integer
  9868. chr = feeder(index++);
  9869. }
  9870. return hash;
  9871. };
  9872. /**
  9873. * Returns a promise that resolves after the given amount of time.
  9874. * @param delay Number of milliseconds to delay
  9875. * @returns Promise that resolves after the given amount of time
  9876. */
  9877. Tools.DelayAsync = function (delay) {
  9878. return new Promise(function (resolve) {
  9879. setTimeout(function () {
  9880. resolve();
  9881. }, delay);
  9882. });
  9883. };
  9884. Tools.BaseUrl = "";
  9885. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9886. /**
  9887. * Default behaviour for cors in the application.
  9888. * It can be a string if the expected behavior is identical in the entire app.
  9889. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9890. */
  9891. Tools.CorsBehavior = "anonymous";
  9892. Tools.UseFallbackTexture = true;
  9893. /**
  9894. * Use this object to register external classes like custom textures or material
  9895. * to allow the laoders to instantiate them
  9896. */
  9897. Tools.RegisteredExternalClasses = {};
  9898. // Used in case of a texture loading problem
  9899. 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";
  9900. Tools._tmpFloatArray = new Float32Array(1);
  9901. Tools.PreprocessUrl = function (url) {
  9902. return url;
  9903. };
  9904. // Logs
  9905. Tools._NoneLogLevel = 0;
  9906. Tools._MessageLogLevel = 1;
  9907. Tools._WarningLogLevel = 2;
  9908. Tools._ErrorLogLevel = 4;
  9909. Tools._LogCache = "";
  9910. Tools.errorsCount = 0;
  9911. Tools.Log = Tools._LogEnabled;
  9912. Tools.Warn = Tools._WarnEnabled;
  9913. Tools.Error = Tools._ErrorEnabled;
  9914. // Performances
  9915. Tools._PerformanceNoneLogLevel = 0;
  9916. Tools._PerformanceUserMarkLogLevel = 1;
  9917. Tools._PerformanceConsoleLogLevel = 2;
  9918. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9919. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9920. return Tools;
  9921. }());
  9922. BABYLON.Tools = Tools;
  9923. /**
  9924. * This class is used to track a performance counter which is number based.
  9925. * The user has access to many properties which give statistics of different nature
  9926. *
  9927. * The implementer can track two kinds of Performance Counter: time and count
  9928. * 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.
  9929. * 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.
  9930. */
  9931. var PerfCounter = /** @class */ (function () {
  9932. function PerfCounter() {
  9933. this._startMonitoringTime = 0;
  9934. this._min = 0;
  9935. this._max = 0;
  9936. this._average = 0;
  9937. this._lastSecAverage = 0;
  9938. this._current = 0;
  9939. this._totalValueCount = 0;
  9940. this._totalAccumulated = 0;
  9941. this._lastSecAccumulated = 0;
  9942. this._lastSecTime = 0;
  9943. this._lastSecValueCount = 0;
  9944. }
  9945. Object.defineProperty(PerfCounter.prototype, "min", {
  9946. /**
  9947. * Returns the smallest value ever
  9948. */
  9949. get: function () {
  9950. return this._min;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(PerfCounter.prototype, "max", {
  9956. /**
  9957. * Returns the biggest value ever
  9958. */
  9959. get: function () {
  9960. return this._max;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(PerfCounter.prototype, "average", {
  9966. /**
  9967. * Returns the average value since the performance counter is running
  9968. */
  9969. get: function () {
  9970. return this._average;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9976. /**
  9977. * Returns the average value of the last second the counter was monitored
  9978. */
  9979. get: function () {
  9980. return this._lastSecAverage;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(PerfCounter.prototype, "current", {
  9986. /**
  9987. * Returns the current value
  9988. */
  9989. get: function () {
  9990. return this._current;
  9991. },
  9992. enumerable: true,
  9993. configurable: true
  9994. });
  9995. Object.defineProperty(PerfCounter.prototype, "total", {
  9996. get: function () {
  9997. return this._totalAccumulated;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(PerfCounter.prototype, "count", {
  10003. get: function () {
  10004. return this._totalValueCount;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. /**
  10010. * Call this method to start monitoring a new frame.
  10011. * 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.
  10012. */
  10013. PerfCounter.prototype.fetchNewFrame = function () {
  10014. this._totalValueCount++;
  10015. this._current = 0;
  10016. this._lastSecValueCount++;
  10017. };
  10018. /**
  10019. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10020. * @param newCount the count value to add to the monitored count
  10021. * @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.
  10022. */
  10023. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10024. if (!PerfCounter.Enabled) {
  10025. return;
  10026. }
  10027. this._current += newCount;
  10028. if (fetchResult) {
  10029. this._fetchResult();
  10030. }
  10031. };
  10032. /**
  10033. * Start monitoring this performance counter
  10034. */
  10035. PerfCounter.prototype.beginMonitoring = function () {
  10036. if (!PerfCounter.Enabled) {
  10037. return;
  10038. }
  10039. this._startMonitoringTime = Tools.Now;
  10040. };
  10041. /**
  10042. * Compute the time lapsed since the previous beginMonitoring() call.
  10043. * @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
  10044. */
  10045. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10046. if (newFrame === void 0) { newFrame = true; }
  10047. if (!PerfCounter.Enabled) {
  10048. return;
  10049. }
  10050. if (newFrame) {
  10051. this.fetchNewFrame();
  10052. }
  10053. var currentTime = Tools.Now;
  10054. this._current = currentTime - this._startMonitoringTime;
  10055. if (newFrame) {
  10056. this._fetchResult();
  10057. }
  10058. };
  10059. PerfCounter.prototype._fetchResult = function () {
  10060. this._totalAccumulated += this._current;
  10061. this._lastSecAccumulated += this._current;
  10062. // Min/Max update
  10063. this._min = Math.min(this._min, this._current);
  10064. this._max = Math.max(this._max, this._current);
  10065. this._average = this._totalAccumulated / this._totalValueCount;
  10066. // Reset last sec?
  10067. var now = Tools.Now;
  10068. if ((now - this._lastSecTime) > 1000) {
  10069. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10070. this._lastSecTime = now;
  10071. this._lastSecAccumulated = 0;
  10072. this._lastSecValueCount = 0;
  10073. }
  10074. };
  10075. PerfCounter.Enabled = true;
  10076. return PerfCounter;
  10077. }());
  10078. BABYLON.PerfCounter = PerfCounter;
  10079. /**
  10080. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10081. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10082. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10083. * @param name The name of the class, case should be preserved
  10084. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10085. */
  10086. function className(name, module) {
  10087. return function (target) {
  10088. target["__bjsclassName__"] = name;
  10089. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10090. };
  10091. }
  10092. BABYLON.className = className;
  10093. /**
  10094. * An implementation of a loop for asynchronous functions.
  10095. */
  10096. var AsyncLoop = /** @class */ (function () {
  10097. /**
  10098. * Constroctor.
  10099. * @param iterations the number of iterations.
  10100. * @param _fn the function to run each iteration
  10101. * @param _successCallback the callback that will be called upon succesful execution
  10102. * @param offset starting offset.
  10103. */
  10104. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10105. if (offset === void 0) { offset = 0; }
  10106. this.iterations = iterations;
  10107. this._fn = _fn;
  10108. this._successCallback = _successCallback;
  10109. this.index = offset - 1;
  10110. this._done = false;
  10111. }
  10112. /**
  10113. * Execute the next iteration. Must be called after the last iteration was finished.
  10114. */
  10115. AsyncLoop.prototype.executeNext = function () {
  10116. if (!this._done) {
  10117. if (this.index + 1 < this.iterations) {
  10118. ++this.index;
  10119. this._fn(this);
  10120. }
  10121. else {
  10122. this.breakLoop();
  10123. }
  10124. }
  10125. };
  10126. /**
  10127. * Break the loop and run the success callback.
  10128. */
  10129. AsyncLoop.prototype.breakLoop = function () {
  10130. this._done = true;
  10131. this._successCallback();
  10132. };
  10133. /**
  10134. * Helper function
  10135. */
  10136. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10137. if (offset === void 0) { offset = 0; }
  10138. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10139. loop.executeNext();
  10140. return loop;
  10141. };
  10142. /**
  10143. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10144. * @param iterations total number of iterations
  10145. * @param syncedIterations number of synchronous iterations in each async iteration.
  10146. * @param fn the function to call each iteration.
  10147. * @param callback a success call back that will be called when iterating stops.
  10148. * @param breakFunction a break condition (optional)
  10149. * @param timeout timeout settings for the setTimeout function. default - 0.
  10150. * @constructor
  10151. */
  10152. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10153. if (timeout === void 0) { timeout = 0; }
  10154. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10155. if (breakFunction && breakFunction())
  10156. loop.breakLoop();
  10157. else {
  10158. setTimeout(function () {
  10159. for (var i = 0; i < syncedIterations; ++i) {
  10160. var iteration = (loop.index * syncedIterations) + i;
  10161. if (iteration >= iterations)
  10162. break;
  10163. fn(iteration);
  10164. if (breakFunction && breakFunction()) {
  10165. loop.breakLoop();
  10166. break;
  10167. }
  10168. }
  10169. loop.executeNext();
  10170. }, timeout);
  10171. }
  10172. }, callback);
  10173. };
  10174. return AsyncLoop;
  10175. }());
  10176. BABYLON.AsyncLoop = AsyncLoop;
  10177. })(BABYLON || (BABYLON = {}));
  10178. //# sourceMappingURL=babylon.tools.js.map
  10179. var BABYLON;
  10180. (function (BABYLON) {
  10181. var PromiseStates;
  10182. (function (PromiseStates) {
  10183. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10184. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10185. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10186. })(PromiseStates || (PromiseStates = {}));
  10187. var FulFillmentAgregator = /** @class */ (function () {
  10188. function FulFillmentAgregator() {
  10189. this.count = 0;
  10190. this.target = 0;
  10191. this.results = [];
  10192. }
  10193. return FulFillmentAgregator;
  10194. }());
  10195. var InternalPromise = /** @class */ (function () {
  10196. function InternalPromise(resolver) {
  10197. var _this = this;
  10198. this._state = PromiseStates.Pending;
  10199. this._children = new Array();
  10200. this._rejectWasConsumed = false;
  10201. if (!resolver) {
  10202. return;
  10203. }
  10204. try {
  10205. resolver(function (value) {
  10206. _this._resolve(value);
  10207. }, function (reason) {
  10208. _this._reject(reason);
  10209. });
  10210. }
  10211. catch (e) {
  10212. this._reject(e);
  10213. }
  10214. }
  10215. Object.defineProperty(InternalPromise.prototype, "_result", {
  10216. get: function () {
  10217. return this._resultValue;
  10218. },
  10219. set: function (value) {
  10220. this._resultValue = value;
  10221. if (this._parent && this._parent._result === undefined) {
  10222. this._parent._result = value;
  10223. }
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. InternalPromise.prototype.catch = function (onRejected) {
  10229. return this.then(undefined, onRejected);
  10230. };
  10231. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10232. var _this = this;
  10233. var newPromise = new InternalPromise();
  10234. newPromise._onFulfilled = onFulfilled;
  10235. newPromise._onRejected = onRejected;
  10236. // Composition
  10237. this._children.push(newPromise);
  10238. newPromise._parent = this;
  10239. if (this._state !== PromiseStates.Pending) {
  10240. BABYLON.Tools.SetImmediate(function () {
  10241. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10242. var returnedValue = newPromise._resolve(_this._result);
  10243. if (returnedValue !== undefined && returnedValue !== null) {
  10244. if (returnedValue._state !== undefined) {
  10245. var returnedPromise = returnedValue;
  10246. newPromise._children.push(returnedPromise);
  10247. returnedPromise._parent = newPromise;
  10248. newPromise = returnedPromise;
  10249. }
  10250. else {
  10251. newPromise._result = returnedValue;
  10252. }
  10253. }
  10254. }
  10255. else {
  10256. newPromise._reject(_this._reason);
  10257. }
  10258. });
  10259. }
  10260. return newPromise;
  10261. };
  10262. InternalPromise.prototype._moveChildren = function (children) {
  10263. var _this = this;
  10264. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10265. this._children.forEach(function (child) {
  10266. child._parent = _this;
  10267. });
  10268. if (this._state === PromiseStates.Fulfilled) {
  10269. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10270. var child = _b[_i];
  10271. child._resolve(this._result);
  10272. }
  10273. }
  10274. else if (this._state === PromiseStates.Rejected) {
  10275. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10276. var child = _d[_c];
  10277. child._reject(this._reason);
  10278. }
  10279. }
  10280. var _a;
  10281. };
  10282. InternalPromise.prototype._resolve = function (value) {
  10283. try {
  10284. this._state = PromiseStates.Fulfilled;
  10285. var returnedValue = null;
  10286. if (this._onFulfilled) {
  10287. returnedValue = this._onFulfilled(value);
  10288. }
  10289. if (returnedValue !== undefined && returnedValue !== null) {
  10290. if (returnedValue._state !== undefined) {
  10291. // Transmit children
  10292. var returnedPromise = returnedValue;
  10293. returnedPromise._parent = this;
  10294. returnedPromise._moveChildren(this._children);
  10295. value = returnedPromise._result;
  10296. }
  10297. else {
  10298. value = returnedValue;
  10299. }
  10300. }
  10301. this._result = value;
  10302. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10303. var child = _a[_i];
  10304. child._resolve(value);
  10305. }
  10306. this._children.length = 0;
  10307. delete this._onFulfilled;
  10308. delete this._onRejected;
  10309. }
  10310. catch (e) {
  10311. this._reject(e, true);
  10312. }
  10313. };
  10314. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10315. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10316. this._state = PromiseStates.Rejected;
  10317. this._reason = reason;
  10318. if (this._onRejected && !onLocalThrow) {
  10319. try {
  10320. this._onRejected(reason);
  10321. this._rejectWasConsumed = true;
  10322. }
  10323. catch (e) {
  10324. reason = e;
  10325. }
  10326. }
  10327. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10328. var child = _a[_i];
  10329. if (this._rejectWasConsumed) {
  10330. child._resolve(null);
  10331. }
  10332. else {
  10333. child._reject(reason);
  10334. }
  10335. }
  10336. this._children.length = 0;
  10337. delete this._onFulfilled;
  10338. delete this._onRejected;
  10339. };
  10340. InternalPromise.resolve = function (value) {
  10341. var newPromise = new InternalPromise();
  10342. newPromise._resolve(value);
  10343. return newPromise;
  10344. };
  10345. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10346. promise.then(function (value) {
  10347. agregator.results[index] = value;
  10348. agregator.count++;
  10349. if (agregator.count === agregator.target) {
  10350. agregator.rootPromise._resolve(agregator.results);
  10351. }
  10352. return null;
  10353. }, function (reason) {
  10354. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10355. agregator.rootPromise._reject(reason);
  10356. }
  10357. });
  10358. };
  10359. InternalPromise.all = function (promises) {
  10360. var newPromise = new InternalPromise();
  10361. var agregator = new FulFillmentAgregator();
  10362. agregator.target = promises.length;
  10363. agregator.rootPromise = newPromise;
  10364. if (promises.length) {
  10365. for (var index = 0; index < promises.length; index++) {
  10366. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10367. }
  10368. }
  10369. else {
  10370. newPromise._resolve([]);
  10371. }
  10372. return newPromise;
  10373. };
  10374. InternalPromise.race = function (promises) {
  10375. var newPromise = new InternalPromise();
  10376. if (promises.length) {
  10377. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10378. var promise = promises_1[_i];
  10379. promise.then(function (value) {
  10380. if (newPromise) {
  10381. newPromise._resolve(value);
  10382. newPromise = null;
  10383. }
  10384. return null;
  10385. }, function (reason) {
  10386. if (newPromise) {
  10387. newPromise._reject(reason);
  10388. newPromise = null;
  10389. }
  10390. });
  10391. }
  10392. }
  10393. return newPromise;
  10394. };
  10395. return InternalPromise;
  10396. }());
  10397. /**
  10398. * Helper class that provides a small promise polyfill
  10399. */
  10400. var PromisePolyfill = /** @class */ (function () {
  10401. function PromisePolyfill() {
  10402. }
  10403. /**
  10404. * Static function used to check if the polyfill is required
  10405. * If this is the case then the function will inject the polyfill to window.Promise
  10406. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10407. */
  10408. PromisePolyfill.Apply = function (force) {
  10409. if (force === void 0) { force = false; }
  10410. if (force || typeof Promise === 'undefined') {
  10411. var root = window;
  10412. root.Promise = InternalPromise;
  10413. }
  10414. };
  10415. return PromisePolyfill;
  10416. }());
  10417. BABYLON.PromisePolyfill = PromisePolyfill;
  10418. })(BABYLON || (BABYLON = {}));
  10419. //# sourceMappingURL=babylon.promise.js.map
  10420. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10421. var BABYLON;
  10422. (function (BABYLON) {
  10423. /**
  10424. * Helper class to push actions to a pool of workers.
  10425. */
  10426. var WorkerPool = /** @class */ (function () {
  10427. /**
  10428. * Constructor
  10429. * @param workers Array of workers to use for actions
  10430. */
  10431. function WorkerPool(workers) {
  10432. this._pendingActions = new Array();
  10433. this._workerInfos = workers.map(function (worker) { return ({
  10434. worker: worker,
  10435. active: false
  10436. }); });
  10437. }
  10438. /**
  10439. * Terminates all workers and clears any pending actions.
  10440. */
  10441. WorkerPool.prototype.dispose = function () {
  10442. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10443. var workerInfo = _a[_i];
  10444. workerInfo.worker.terminate();
  10445. }
  10446. delete this._workerInfos;
  10447. delete this._pendingActions;
  10448. };
  10449. /**
  10450. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10451. * pended until a worker has completed its action.
  10452. * @param action The action to perform. Call onComplete when the action is complete.
  10453. */
  10454. WorkerPool.prototype.push = function (action) {
  10455. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10456. var workerInfo = _a[_i];
  10457. if (!workerInfo.active) {
  10458. this._execute(workerInfo, action);
  10459. return;
  10460. }
  10461. }
  10462. this._pendingActions.push(action);
  10463. };
  10464. WorkerPool.prototype._execute = function (workerInfo, action) {
  10465. var _this = this;
  10466. workerInfo.active = true;
  10467. action(workerInfo.worker, function () {
  10468. workerInfo.active = false;
  10469. var nextAction = _this._pendingActions.shift();
  10470. if (nextAction) {
  10471. _this._execute(workerInfo, nextAction);
  10472. }
  10473. });
  10474. };
  10475. return WorkerPool;
  10476. }());
  10477. BABYLON.WorkerPool = WorkerPool;
  10478. })(BABYLON || (BABYLON = {}));
  10479. //# sourceMappingURL=babylon.workerPool.js.map
  10480. var BABYLON;
  10481. (function (BABYLON) {
  10482. /**
  10483. * @hidden
  10484. **/
  10485. var _AlphaState = /** @class */ (function () {
  10486. /**
  10487. * Initializes the state.
  10488. */
  10489. function _AlphaState() {
  10490. this._isAlphaBlendDirty = false;
  10491. this._isBlendFunctionParametersDirty = false;
  10492. this._isBlendEquationParametersDirty = false;
  10493. this._isBlendConstantsDirty = false;
  10494. this._alphaBlend = false;
  10495. this._blendFunctionParameters = new Array(4);
  10496. this._blendEquationParameters = new Array(2);
  10497. this._blendConstants = new Array(4);
  10498. this.reset();
  10499. }
  10500. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10501. get: function () {
  10502. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10503. },
  10504. enumerable: true,
  10505. configurable: true
  10506. });
  10507. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10508. get: function () {
  10509. return this._alphaBlend;
  10510. },
  10511. set: function (value) {
  10512. if (this._alphaBlend === value) {
  10513. return;
  10514. }
  10515. this._alphaBlend = value;
  10516. this._isAlphaBlendDirty = true;
  10517. },
  10518. enumerable: true,
  10519. configurable: true
  10520. });
  10521. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10522. if (this._blendConstants[0] === r &&
  10523. this._blendConstants[1] === g &&
  10524. this._blendConstants[2] === b &&
  10525. this._blendConstants[3] === a) {
  10526. return;
  10527. }
  10528. this._blendConstants[0] = r;
  10529. this._blendConstants[1] = g;
  10530. this._blendConstants[2] = b;
  10531. this._blendConstants[3] = a;
  10532. this._isBlendConstantsDirty = true;
  10533. };
  10534. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10535. if (this._blendFunctionParameters[0] === value0 &&
  10536. this._blendFunctionParameters[1] === value1 &&
  10537. this._blendFunctionParameters[2] === value2 &&
  10538. this._blendFunctionParameters[3] === value3) {
  10539. return;
  10540. }
  10541. this._blendFunctionParameters[0] = value0;
  10542. this._blendFunctionParameters[1] = value1;
  10543. this._blendFunctionParameters[2] = value2;
  10544. this._blendFunctionParameters[3] = value3;
  10545. this._isBlendFunctionParametersDirty = true;
  10546. };
  10547. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10548. if (this._blendEquationParameters[0] === rgb &&
  10549. this._blendEquationParameters[1] === alpha) {
  10550. return;
  10551. }
  10552. this._blendEquationParameters[0] = rgb;
  10553. this._blendEquationParameters[1] = alpha;
  10554. this._isBlendEquationParametersDirty = true;
  10555. };
  10556. _AlphaState.prototype.reset = function () {
  10557. this._alphaBlend = false;
  10558. this._blendFunctionParameters[0] = null;
  10559. this._blendFunctionParameters[1] = null;
  10560. this._blendFunctionParameters[2] = null;
  10561. this._blendFunctionParameters[3] = null;
  10562. this._blendEquationParameters[0] = null;
  10563. this._blendEquationParameters[1] = null;
  10564. this._blendConstants[0] = null;
  10565. this._blendConstants[1] = null;
  10566. this._blendConstants[2] = null;
  10567. this._blendConstants[3] = null;
  10568. this._isAlphaBlendDirty = true;
  10569. this._isBlendFunctionParametersDirty = false;
  10570. this._isBlendEquationParametersDirty = false;
  10571. this._isBlendConstantsDirty = false;
  10572. };
  10573. _AlphaState.prototype.apply = function (gl) {
  10574. if (!this.isDirty) {
  10575. return;
  10576. }
  10577. // Alpha blend
  10578. if (this._isAlphaBlendDirty) {
  10579. if (this._alphaBlend) {
  10580. gl.enable(gl.BLEND);
  10581. }
  10582. else {
  10583. gl.disable(gl.BLEND);
  10584. }
  10585. this._isAlphaBlendDirty = false;
  10586. }
  10587. // Alpha function
  10588. if (this._isBlendFunctionParametersDirty) {
  10589. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10590. this._isBlendFunctionParametersDirty = false;
  10591. }
  10592. // Alpha equation
  10593. if (this._isBlendEquationParametersDirty) {
  10594. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10595. this._isBlendEquationParametersDirty = false;
  10596. }
  10597. // Constants
  10598. if (this._isBlendConstantsDirty) {
  10599. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10600. this._isBlendConstantsDirty = false;
  10601. }
  10602. };
  10603. return _AlphaState;
  10604. }());
  10605. BABYLON._AlphaState = _AlphaState;
  10606. })(BABYLON || (BABYLON = {}));
  10607. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10608. var BABYLON;
  10609. (function (BABYLON) {
  10610. /**
  10611. * @hidden
  10612. **/
  10613. var _DepthCullingState = /** @class */ (function () {
  10614. /**
  10615. * Initializes the state.
  10616. */
  10617. function _DepthCullingState() {
  10618. this._isDepthTestDirty = false;
  10619. this._isDepthMaskDirty = false;
  10620. this._isDepthFuncDirty = false;
  10621. this._isCullFaceDirty = false;
  10622. this._isCullDirty = false;
  10623. this._isZOffsetDirty = false;
  10624. this._isFrontFaceDirty = false;
  10625. this.reset();
  10626. }
  10627. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10628. get: function () {
  10629. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10630. },
  10631. enumerable: true,
  10632. configurable: true
  10633. });
  10634. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10635. get: function () {
  10636. return this._zOffset;
  10637. },
  10638. set: function (value) {
  10639. if (this._zOffset === value) {
  10640. return;
  10641. }
  10642. this._zOffset = value;
  10643. this._isZOffsetDirty = true;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10649. get: function () {
  10650. return this._cullFace;
  10651. },
  10652. set: function (value) {
  10653. if (this._cullFace === value) {
  10654. return;
  10655. }
  10656. this._cullFace = value;
  10657. this._isCullFaceDirty = true;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10663. get: function () {
  10664. return this._cull;
  10665. },
  10666. set: function (value) {
  10667. if (this._cull === value) {
  10668. return;
  10669. }
  10670. this._cull = value;
  10671. this._isCullDirty = true;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10677. get: function () {
  10678. return this._depthFunc;
  10679. },
  10680. set: function (value) {
  10681. if (this._depthFunc === value) {
  10682. return;
  10683. }
  10684. this._depthFunc = value;
  10685. this._isDepthFuncDirty = true;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10691. get: function () {
  10692. return this._depthMask;
  10693. },
  10694. set: function (value) {
  10695. if (this._depthMask === value) {
  10696. return;
  10697. }
  10698. this._depthMask = value;
  10699. this._isDepthMaskDirty = true;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10705. get: function () {
  10706. return this._depthTest;
  10707. },
  10708. set: function (value) {
  10709. if (this._depthTest === value) {
  10710. return;
  10711. }
  10712. this._depthTest = value;
  10713. this._isDepthTestDirty = true;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10719. get: function () {
  10720. return this._frontFace;
  10721. },
  10722. set: function (value) {
  10723. if (this._frontFace === value) {
  10724. return;
  10725. }
  10726. this._frontFace = value;
  10727. this._isFrontFaceDirty = true;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. _DepthCullingState.prototype.reset = function () {
  10733. this._depthMask = true;
  10734. this._depthTest = true;
  10735. this._depthFunc = null;
  10736. this._cullFace = null;
  10737. this._cull = null;
  10738. this._zOffset = 0;
  10739. this._frontFace = null;
  10740. this._isDepthTestDirty = true;
  10741. this._isDepthMaskDirty = true;
  10742. this._isDepthFuncDirty = false;
  10743. this._isCullFaceDirty = false;
  10744. this._isCullDirty = false;
  10745. this._isZOffsetDirty = false;
  10746. this._isFrontFaceDirty = false;
  10747. };
  10748. _DepthCullingState.prototype.apply = function (gl) {
  10749. if (!this.isDirty) {
  10750. return;
  10751. }
  10752. // Cull
  10753. if (this._isCullDirty) {
  10754. if (this.cull) {
  10755. gl.enable(gl.CULL_FACE);
  10756. }
  10757. else {
  10758. gl.disable(gl.CULL_FACE);
  10759. }
  10760. this._isCullDirty = false;
  10761. }
  10762. // Cull face
  10763. if (this._isCullFaceDirty) {
  10764. gl.cullFace(this.cullFace);
  10765. this._isCullFaceDirty = false;
  10766. }
  10767. // Depth mask
  10768. if (this._isDepthMaskDirty) {
  10769. gl.depthMask(this.depthMask);
  10770. this._isDepthMaskDirty = false;
  10771. }
  10772. // Depth test
  10773. if (this._isDepthTestDirty) {
  10774. if (this.depthTest) {
  10775. gl.enable(gl.DEPTH_TEST);
  10776. }
  10777. else {
  10778. gl.disable(gl.DEPTH_TEST);
  10779. }
  10780. this._isDepthTestDirty = false;
  10781. }
  10782. // Depth func
  10783. if (this._isDepthFuncDirty) {
  10784. gl.depthFunc(this.depthFunc);
  10785. this._isDepthFuncDirty = false;
  10786. }
  10787. // zOffset
  10788. if (this._isZOffsetDirty) {
  10789. if (this.zOffset) {
  10790. gl.enable(gl.POLYGON_OFFSET_FILL);
  10791. gl.polygonOffset(this.zOffset, 0);
  10792. }
  10793. else {
  10794. gl.disable(gl.POLYGON_OFFSET_FILL);
  10795. }
  10796. this._isZOffsetDirty = false;
  10797. }
  10798. // Front face
  10799. if (this._isFrontFaceDirty) {
  10800. gl.frontFace(this.frontFace);
  10801. this._isFrontFaceDirty = false;
  10802. }
  10803. };
  10804. return _DepthCullingState;
  10805. }());
  10806. BABYLON._DepthCullingState = _DepthCullingState;
  10807. })(BABYLON || (BABYLON = {}));
  10808. //# sourceMappingURL=babylon.depthCullingState.js.map
  10809. var BABYLON;
  10810. (function (BABYLON) {
  10811. /**
  10812. * @hidden
  10813. **/
  10814. var _StencilState = /** @class */ (function () {
  10815. function _StencilState() {
  10816. this._isStencilTestDirty = false;
  10817. this._isStencilMaskDirty = false;
  10818. this._isStencilFuncDirty = false;
  10819. this._isStencilOpDirty = false;
  10820. this.reset();
  10821. }
  10822. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10823. get: function () {
  10824. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10830. get: function () {
  10831. return this._stencilFunc;
  10832. },
  10833. set: function (value) {
  10834. if (this._stencilFunc === value) {
  10835. return;
  10836. }
  10837. this._stencilFunc = value;
  10838. this._isStencilFuncDirty = true;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10844. get: function () {
  10845. return this._stencilFuncRef;
  10846. },
  10847. set: function (value) {
  10848. if (this._stencilFuncRef === value) {
  10849. return;
  10850. }
  10851. this._stencilFuncRef = value;
  10852. this._isStencilFuncDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10858. get: function () {
  10859. return this._stencilFuncMask;
  10860. },
  10861. set: function (value) {
  10862. if (this._stencilFuncMask === value) {
  10863. return;
  10864. }
  10865. this._stencilFuncMask = value;
  10866. this._isStencilFuncDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10872. get: function () {
  10873. return this._stencilOpStencilFail;
  10874. },
  10875. set: function (value) {
  10876. if (this._stencilOpStencilFail === value) {
  10877. return;
  10878. }
  10879. this._stencilOpStencilFail = value;
  10880. this._isStencilOpDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10886. get: function () {
  10887. return this._stencilOpDepthFail;
  10888. },
  10889. set: function (value) {
  10890. if (this._stencilOpDepthFail === value) {
  10891. return;
  10892. }
  10893. this._stencilOpDepthFail = value;
  10894. this._isStencilOpDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10900. get: function () {
  10901. return this._stencilOpStencilDepthPass;
  10902. },
  10903. set: function (value) {
  10904. if (this._stencilOpStencilDepthPass === value) {
  10905. return;
  10906. }
  10907. this._stencilOpStencilDepthPass = value;
  10908. this._isStencilOpDirty = true;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10914. get: function () {
  10915. return this._stencilMask;
  10916. },
  10917. set: function (value) {
  10918. if (this._stencilMask === value) {
  10919. return;
  10920. }
  10921. this._stencilMask = value;
  10922. this._isStencilMaskDirty = true;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10928. get: function () {
  10929. return this._stencilTest;
  10930. },
  10931. set: function (value) {
  10932. if (this._stencilTest === value) {
  10933. return;
  10934. }
  10935. this._stencilTest = value;
  10936. this._isStencilTestDirty = true;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. _StencilState.prototype.reset = function () {
  10942. this._stencilTest = false;
  10943. this._stencilMask = 0xFF;
  10944. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10945. this._stencilFuncRef = 1;
  10946. this._stencilFuncMask = 0xFF;
  10947. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10948. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10949. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10950. this._isStencilTestDirty = true;
  10951. this._isStencilMaskDirty = true;
  10952. this._isStencilFuncDirty = true;
  10953. this._isStencilOpDirty = true;
  10954. };
  10955. _StencilState.prototype.apply = function (gl) {
  10956. if (!this.isDirty) {
  10957. return;
  10958. }
  10959. // Stencil test
  10960. if (this._isStencilTestDirty) {
  10961. if (this.stencilTest) {
  10962. gl.enable(gl.STENCIL_TEST);
  10963. }
  10964. else {
  10965. gl.disable(gl.STENCIL_TEST);
  10966. }
  10967. this._isStencilTestDirty = false;
  10968. }
  10969. // Stencil mask
  10970. if (this._isStencilMaskDirty) {
  10971. gl.stencilMask(this.stencilMask);
  10972. this._isStencilMaskDirty = false;
  10973. }
  10974. // Stencil func
  10975. if (this._isStencilFuncDirty) {
  10976. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10977. this._isStencilFuncDirty = false;
  10978. }
  10979. // Stencil op
  10980. if (this._isStencilOpDirty) {
  10981. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10982. this._isStencilOpDirty = false;
  10983. }
  10984. };
  10985. return _StencilState;
  10986. }());
  10987. BABYLON._StencilState = _StencilState;
  10988. })(BABYLON || (BABYLON = {}));
  10989. //# sourceMappingURL=babylon.stencilState.js.map
  10990. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10991. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10992. s = arguments[i];
  10993. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10994. t[p] = s[p];
  10995. }
  10996. return t;
  10997. };
  10998. var BABYLON;
  10999. (function (BABYLON) {
  11000. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11001. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11002. };
  11003. var compileRawShader = function (gl, source, type) {
  11004. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11005. gl.shaderSource(shader, source);
  11006. gl.compileShader(shader);
  11007. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11008. var log = gl.getShaderInfoLog(shader);
  11009. if (log) {
  11010. throw new Error(log);
  11011. }
  11012. }
  11013. if (!shader) {
  11014. throw new Error("Something went wrong while compile the shader.");
  11015. }
  11016. return shader;
  11017. };
  11018. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11019. var magFilter = gl.NEAREST;
  11020. var minFilter = gl.NEAREST;
  11021. switch (samplingMode) {
  11022. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11023. magFilter = gl.LINEAR;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.LINEAR;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11032. magFilter = gl.LINEAR;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11035. }
  11036. else {
  11037. minFilter = gl.LINEAR;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11041. magFilter = gl.NEAREST;
  11042. if (generateMipMaps) {
  11043. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11044. }
  11045. else {
  11046. minFilter = gl.NEAREST;
  11047. }
  11048. break;
  11049. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11050. magFilter = gl.NEAREST;
  11051. if (generateMipMaps) {
  11052. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11053. }
  11054. else {
  11055. minFilter = gl.NEAREST;
  11056. }
  11057. break;
  11058. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11059. magFilter = gl.NEAREST;
  11060. if (generateMipMaps) {
  11061. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11062. }
  11063. else {
  11064. minFilter = gl.LINEAR;
  11065. }
  11066. break;
  11067. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11068. magFilter = gl.NEAREST;
  11069. if (generateMipMaps) {
  11070. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11071. }
  11072. else {
  11073. minFilter = gl.LINEAR;
  11074. }
  11075. break;
  11076. case BABYLON.Texture.NEAREST_LINEAR:
  11077. magFilter = gl.NEAREST;
  11078. minFilter = gl.LINEAR;
  11079. break;
  11080. case BABYLON.Texture.NEAREST_NEAREST:
  11081. magFilter = gl.NEAREST;
  11082. minFilter = gl.NEAREST;
  11083. break;
  11084. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11085. magFilter = gl.LINEAR;
  11086. if (generateMipMaps) {
  11087. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11088. }
  11089. else {
  11090. minFilter = gl.NEAREST;
  11091. }
  11092. break;
  11093. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11094. magFilter = gl.LINEAR;
  11095. if (generateMipMaps) {
  11096. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11097. }
  11098. else {
  11099. minFilter = gl.NEAREST;
  11100. }
  11101. break;
  11102. case BABYLON.Texture.LINEAR_LINEAR:
  11103. magFilter = gl.LINEAR;
  11104. minFilter = gl.LINEAR;
  11105. break;
  11106. case BABYLON.Texture.LINEAR_NEAREST:
  11107. magFilter = gl.LINEAR;
  11108. minFilter = gl.NEAREST;
  11109. break;
  11110. }
  11111. return {
  11112. min: minFilter,
  11113. mag: magFilter
  11114. };
  11115. };
  11116. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11117. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11118. var img;
  11119. var onload = function () {
  11120. loadedImages[index] = img;
  11121. loadedImages._internalCount++;
  11122. if (scene) {
  11123. scene._removePendingData(img);
  11124. }
  11125. if (loadedImages._internalCount === 6) {
  11126. onfinish(loadedImages);
  11127. }
  11128. };
  11129. var onerror = function (message, exception) {
  11130. if (scene) {
  11131. scene._removePendingData(img);
  11132. }
  11133. if (onErrorCallBack) {
  11134. onErrorCallBack(message, exception);
  11135. }
  11136. };
  11137. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11138. if (scene) {
  11139. scene._addPendingData(img);
  11140. }
  11141. };
  11142. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11143. if (onError === void 0) { onError = null; }
  11144. var loadedImages = [];
  11145. loadedImages._internalCount = 0;
  11146. for (var index = 0; index < 6; index++) {
  11147. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11148. }
  11149. };
  11150. var BufferPointer = /** @class */ (function () {
  11151. function BufferPointer() {
  11152. }
  11153. return BufferPointer;
  11154. }());
  11155. /**
  11156. * Interface for attribute information associated with buffer instanciation
  11157. */
  11158. var InstancingAttributeInfo = /** @class */ (function () {
  11159. function InstancingAttributeInfo() {
  11160. }
  11161. return InstancingAttributeInfo;
  11162. }());
  11163. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11164. /**
  11165. * Define options used to create a render target texture
  11166. */
  11167. var RenderTargetCreationOptions = /** @class */ (function () {
  11168. function RenderTargetCreationOptions() {
  11169. }
  11170. return RenderTargetCreationOptions;
  11171. }());
  11172. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11173. /**
  11174. * Define options used to create a depth texture
  11175. */
  11176. var DepthTextureCreationOptions = /** @class */ (function () {
  11177. function DepthTextureCreationOptions() {
  11178. }
  11179. return DepthTextureCreationOptions;
  11180. }());
  11181. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11182. /**
  11183. * Class used to describe the capabilities of the engine relatively to the current browser
  11184. */
  11185. var EngineCapabilities = /** @class */ (function () {
  11186. function EngineCapabilities() {
  11187. }
  11188. return EngineCapabilities;
  11189. }());
  11190. BABYLON.EngineCapabilities = EngineCapabilities;
  11191. /**
  11192. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11193. */
  11194. var Engine = /** @class */ (function () {
  11195. /**
  11196. * Creates a new engine
  11197. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11198. * @param antialias defines enable antialiasing (default: false)
  11199. * @param options defines further options to be sent to the getContext() function
  11200. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11201. */
  11202. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11203. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11204. var _this = this;
  11205. // Public members
  11206. /**
  11207. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11208. */
  11209. this.forcePOTTextures = false;
  11210. /**
  11211. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11212. */
  11213. this.isFullscreen = false;
  11214. /**
  11215. * Gets a boolean indicating if the pointer is currently locked
  11216. */
  11217. this.isPointerLock = false;
  11218. /**
  11219. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11220. */
  11221. this.cullBackFaces = true;
  11222. /**
  11223. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11224. */
  11225. this.renderEvenInBackground = true;
  11226. /**
  11227. * Gets or sets a boolean indicating that cache can be kept between frames
  11228. */
  11229. this.preventCacheWipeBetweenFrames = false;
  11230. /**
  11231. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11232. **/
  11233. this.enableOfflineSupport = false;
  11234. /**
  11235. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11236. **/
  11237. this.disableManifestCheck = false;
  11238. /**
  11239. * Gets the list of created scenes
  11240. */
  11241. this.scenes = new Array();
  11242. /**
  11243. * Gets the list of created postprocesses
  11244. */
  11245. this.postProcesses = new Array();
  11246. // Observables
  11247. /**
  11248. * Observable event triggered each time the rendering canvas is resized
  11249. */
  11250. this.onResizeObservable = new BABYLON.Observable();
  11251. /**
  11252. * Observable event triggered each time the canvas loses focus
  11253. */
  11254. this.onCanvasBlurObservable = new BABYLON.Observable();
  11255. /**
  11256. * Observable event triggered each time the canvas gains focus
  11257. */
  11258. this.onCanvasFocusObservable = new BABYLON.Observable();
  11259. /**
  11260. * Observable event triggered each time the canvas receives pointerout event
  11261. */
  11262. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11263. /**
  11264. * Observable event triggered before each texture is initialized
  11265. */
  11266. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11267. //WebVR
  11268. this._vrDisplay = undefined;
  11269. this._vrSupported = false;
  11270. this._vrExclusivePointerMode = false;
  11271. // Uniform buffers list
  11272. /**
  11273. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11274. */
  11275. this.disableUniformBuffers = false;
  11276. /** @hidden */
  11277. this._uniformBuffers = new Array();
  11278. // Observables
  11279. /**
  11280. * Observable raised when the engine begins a new frame
  11281. */
  11282. this.onBeginFrameObservable = new BABYLON.Observable();
  11283. /**
  11284. * Observable raised when the engine ends the current frame
  11285. */
  11286. this.onEndFrameObservable = new BABYLON.Observable();
  11287. /**
  11288. * Observable raised when the engine is about to compile a shader
  11289. */
  11290. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable raised when the engine has jsut compiled a shader
  11293. */
  11294. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11295. this._windowIsBackground = false;
  11296. this._webGLVersion = 1.0;
  11297. /** @hidden */
  11298. this._badOS = false;
  11299. /** @hidden */
  11300. this._badDesktopOS = false;
  11301. /**
  11302. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11303. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11304. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11305. */
  11306. this.disableTextureBindingOptimization = false;
  11307. /**
  11308. * Observable signaled when VR display mode changes
  11309. */
  11310. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11311. /**
  11312. * Observable signaled when VR request present is complete
  11313. */
  11314. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11315. /**
  11316. * Observable signaled when VR request present starts
  11317. */
  11318. this.onVRRequestPresentStart = new BABYLON.Observable();
  11319. this._colorWrite = true;
  11320. /** @hidden */
  11321. this._drawCalls = new BABYLON.PerfCounter();
  11322. /** @hidden */
  11323. this._textureCollisions = new BABYLON.PerfCounter();
  11324. this._renderingQueueLaunched = false;
  11325. this._activeRenderLoops = new Array();
  11326. // Deterministic lockstepMaxSteps
  11327. this._deterministicLockstep = false;
  11328. this._lockstepMaxSteps = 4;
  11329. // Lost context
  11330. /**
  11331. * Observable signaled when a context lost event is raised
  11332. */
  11333. this.onContextLostObservable = new BABYLON.Observable();
  11334. /**
  11335. * Observable signaled when a context restored event is raised
  11336. */
  11337. this.onContextRestoredObservable = new BABYLON.Observable();
  11338. this._contextWasLost = false;
  11339. this._doNotHandleContextLost = false;
  11340. // FPS
  11341. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11342. this._fps = 60;
  11343. this._deltaTime = 0;
  11344. /**
  11345. * Turn this value on if you want to pause FPS computation when in background
  11346. */
  11347. this.disablePerformanceMonitorInBackground = false;
  11348. // States
  11349. /** @hidden */
  11350. this._depthCullingState = new BABYLON._DepthCullingState();
  11351. /** @hidden */
  11352. this._stencilState = new BABYLON._StencilState();
  11353. /** @hidden */
  11354. this._alphaState = new BABYLON._AlphaState();
  11355. /** @hidden */
  11356. this._alphaMode = Engine.ALPHA_DISABLE;
  11357. // Cache
  11358. this._internalTexturesCache = new Array();
  11359. /** @hidden */
  11360. this._activeChannel = 0;
  11361. this._currentTextureChannel = -1;
  11362. /** @hidden */
  11363. this._boundTexturesCache = {};
  11364. this._compiledEffects = {};
  11365. this._vertexAttribArraysEnabled = [];
  11366. this._uintIndicesCurrentlySet = false;
  11367. this._currentBoundBuffer = new Array();
  11368. this._currentBufferPointers = new Array();
  11369. this._currentInstanceLocations = new Array();
  11370. this._currentInstanceBuffers = new Array();
  11371. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11372. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11373. this._vaoRecordInProgress = false;
  11374. this._mustWipeVertexAttributes = false;
  11375. this._nextFreeTextureSlots = new Array();
  11376. this._maxSimultaneousTextures = 0;
  11377. this._activeRequests = new Array();
  11378. // Hardware supported Compressed Textures
  11379. this._texturesSupported = new Array();
  11380. /**
  11381. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11382. */
  11383. this.premultipliedAlpha = true;
  11384. this._onVRFullScreenTriggered = function () {
  11385. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11386. //get the old size before we change
  11387. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11388. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11389. //get the width and height, change the render size
  11390. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11391. _this.setHardwareScalingLevel(1);
  11392. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11393. }
  11394. else {
  11395. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11396. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11397. }
  11398. };
  11399. this._boundUniforms = {};
  11400. // Register promises
  11401. BABYLON.PromisePolyfill.Apply();
  11402. var canvas = null;
  11403. Engine.Instances.push(this);
  11404. if (!canvasOrContext) {
  11405. return;
  11406. }
  11407. options = options || {};
  11408. if (canvasOrContext.getContext) {
  11409. canvas = canvasOrContext;
  11410. this._renderingCanvas = canvas;
  11411. if (antialias != null) {
  11412. options.antialias = antialias;
  11413. }
  11414. if (options.deterministicLockstep === undefined) {
  11415. options.deterministicLockstep = false;
  11416. }
  11417. if (options.lockstepMaxSteps === undefined) {
  11418. options.lockstepMaxSteps = 4;
  11419. }
  11420. if (options.preserveDrawingBuffer === undefined) {
  11421. options.preserveDrawingBuffer = false;
  11422. }
  11423. if (options.audioEngine === undefined) {
  11424. options.audioEngine = true;
  11425. }
  11426. if (options.stencil === undefined) {
  11427. options.stencil = true;
  11428. }
  11429. if (options.premultipliedAlpha) {
  11430. this.premultipliedAlpha = true;
  11431. }
  11432. else {
  11433. this.premultipliedAlpha = false;
  11434. }
  11435. this._deterministicLockstep = options.deterministicLockstep;
  11436. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11437. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11438. // Exceptions
  11439. if (navigator && navigator.userAgent) {
  11440. var ua = navigator.userAgent;
  11441. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11442. var exception = _a[_i];
  11443. var key = exception.key;
  11444. var targets = exception.targets;
  11445. if (ua.indexOf(key) > -1) {
  11446. if (exception.capture && exception.captureConstraint) {
  11447. var capture = exception.capture;
  11448. var constraint = exception.captureConstraint;
  11449. var regex = new RegExp(capture);
  11450. var matches = regex.exec(ua);
  11451. if (matches && matches.length > 0) {
  11452. var capturedValue = parseInt(matches[matches.length - 1]);
  11453. if (capturedValue >= constraint) {
  11454. continue;
  11455. }
  11456. }
  11457. }
  11458. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11459. var target = targets_1[_b];
  11460. switch (target) {
  11461. case "uniformBuffer":
  11462. this.disableUniformBuffers = true;
  11463. break;
  11464. case "textureBindingOptimization":
  11465. this.disableTextureBindingOptimization = true;
  11466. break;
  11467. }
  11468. }
  11469. }
  11470. }
  11471. }
  11472. // GL
  11473. if (!options.disableWebGL2Support) {
  11474. try {
  11475. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11476. if (this._gl) {
  11477. this._webGLVersion = 2.0;
  11478. }
  11479. }
  11480. catch (e) {
  11481. // Do nothing
  11482. }
  11483. }
  11484. if (!this._gl) {
  11485. if (!canvas) {
  11486. throw new Error("The provided canvas is null or undefined.");
  11487. }
  11488. try {
  11489. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11490. }
  11491. catch (e) {
  11492. throw new Error("WebGL not supported");
  11493. }
  11494. }
  11495. if (!this._gl) {
  11496. throw new Error("WebGL not supported");
  11497. }
  11498. this._onCanvasFocus = function () {
  11499. _this.onCanvasFocusObservable.notifyObservers(_this);
  11500. };
  11501. this._onCanvasBlur = function () {
  11502. _this.onCanvasBlurObservable.notifyObservers(_this);
  11503. };
  11504. canvas.addEventListener("focus", this._onCanvasFocus);
  11505. canvas.addEventListener("blur", this._onCanvasBlur);
  11506. this._onBlur = function () {
  11507. if (_this.disablePerformanceMonitorInBackground) {
  11508. _this._performanceMonitor.disable();
  11509. }
  11510. _this._windowIsBackground = true;
  11511. };
  11512. this._onFocus = function () {
  11513. if (_this.disablePerformanceMonitorInBackground) {
  11514. _this._performanceMonitor.enable();
  11515. }
  11516. _this._windowIsBackground = false;
  11517. };
  11518. this._onCanvasPointerOut = function (ev) {
  11519. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11520. };
  11521. window.addEventListener("blur", this._onBlur);
  11522. window.addEventListener("focus", this._onFocus);
  11523. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11524. // Context lost
  11525. if (!this._doNotHandleContextLost) {
  11526. this._onContextLost = function (evt) {
  11527. evt.preventDefault();
  11528. _this._contextWasLost = true;
  11529. BABYLON.Tools.Warn("WebGL context lost.");
  11530. _this.onContextLostObservable.notifyObservers(_this);
  11531. };
  11532. this._onContextRestored = function (evt) {
  11533. // Adding a timeout to avoid race condition at browser level
  11534. setTimeout(function () {
  11535. // Rebuild gl context
  11536. _this._initGLContext();
  11537. // Rebuild effects
  11538. _this._rebuildEffects();
  11539. // Rebuild textures
  11540. _this._rebuildInternalTextures();
  11541. // Rebuild buffers
  11542. _this._rebuildBuffers();
  11543. // Cache
  11544. _this.wipeCaches(true);
  11545. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11546. _this.onContextRestoredObservable.notifyObservers(_this);
  11547. _this._contextWasLost = false;
  11548. }, 0);
  11549. };
  11550. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11551. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11552. }
  11553. }
  11554. else {
  11555. this._gl = canvasOrContext;
  11556. this._renderingCanvas = this._gl.canvas;
  11557. if (this._gl.renderbufferStorageMultisample) {
  11558. this._webGLVersion = 2.0;
  11559. }
  11560. options.stencil = this._gl.getContextAttributes().stencil;
  11561. }
  11562. // Viewport
  11563. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11564. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11565. this.resize();
  11566. this._isStencilEnable = options.stencil ? true : false;
  11567. this._initGLContext();
  11568. if (canvas) {
  11569. // Fullscreen
  11570. this._onFullscreenChange = function () {
  11571. if (document.fullscreen !== undefined) {
  11572. _this.isFullscreen = document.fullscreen;
  11573. }
  11574. else if (document.mozFullScreen !== undefined) {
  11575. _this.isFullscreen = document.mozFullScreen;
  11576. }
  11577. else if (document.webkitIsFullScreen !== undefined) {
  11578. _this.isFullscreen = document.webkitIsFullScreen;
  11579. }
  11580. else if (document.msIsFullScreen !== undefined) {
  11581. _this.isFullscreen = document.msIsFullScreen;
  11582. }
  11583. // Pointer lock
  11584. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11585. canvas.requestPointerLock = canvas.requestPointerLock ||
  11586. canvas.msRequestPointerLock ||
  11587. canvas.mozRequestPointerLock ||
  11588. canvas.webkitRequestPointerLock;
  11589. if (canvas.requestPointerLock) {
  11590. canvas.requestPointerLock();
  11591. }
  11592. }
  11593. };
  11594. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11595. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11596. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11597. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11598. // Pointer lock
  11599. this._onPointerLockChange = function () {
  11600. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11601. document.webkitPointerLockElement === canvas ||
  11602. document.msPointerLockElement === canvas ||
  11603. document.pointerLockElement === canvas);
  11604. };
  11605. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11606. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11607. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11608. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11609. this._onVRDisplayPointerRestricted = function () {
  11610. if (canvas) {
  11611. canvas.requestPointerLock();
  11612. }
  11613. };
  11614. this._onVRDisplayPointerUnrestricted = function () {
  11615. document.exitPointerLock();
  11616. };
  11617. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11618. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11619. }
  11620. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11621. Engine.audioEngine = new BABYLON.AudioEngine();
  11622. }
  11623. // Prepare buffer pointers
  11624. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11625. this._currentBufferPointers[i] = new BufferPointer();
  11626. }
  11627. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11628. // Load WebVR Devices
  11629. if (options.autoEnableWebVR) {
  11630. this.initWebVR();
  11631. }
  11632. // Detect if we are running on a faulty buggy OS.
  11633. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11634. // Detect if we are running on a faulty buggy desktop OS.
  11635. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11636. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11637. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11638. }
  11639. Object.defineProperty(Engine, "LastCreatedEngine", {
  11640. /**
  11641. * Gets the latest created engine
  11642. */
  11643. get: function () {
  11644. if (Engine.Instances.length === 0) {
  11645. return null;
  11646. }
  11647. return Engine.Instances[Engine.Instances.length - 1];
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(Engine, "LastCreatedScene", {
  11653. /**
  11654. * Gets the latest created scene
  11655. */
  11656. get: function () {
  11657. var lastCreatedEngine = Engine.LastCreatedEngine;
  11658. if (!lastCreatedEngine) {
  11659. return null;
  11660. }
  11661. if (lastCreatedEngine.scenes.length === 0) {
  11662. return null;
  11663. }
  11664. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11665. },
  11666. enumerable: true,
  11667. configurable: true
  11668. });
  11669. /**
  11670. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11671. * @param flag defines which part of the materials must be marked as dirty
  11672. * @param predicate defines a predicate used to filter which materials should be affected
  11673. */
  11674. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11675. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11676. var engine = Engine.Instances[engineIndex];
  11677. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11678. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11679. }
  11680. }
  11681. };
  11682. Object.defineProperty(Engine, "NEVER", {
  11683. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11684. get: function () {
  11685. return Engine._NEVER;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine, "ALWAYS", {
  11691. /** 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 */
  11692. get: function () {
  11693. return Engine._ALWAYS;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "LESS", {
  11699. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11700. get: function () {
  11701. return Engine._LESS;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "EQUAL", {
  11707. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11708. get: function () {
  11709. return Engine._EQUAL;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine, "LEQUAL", {
  11715. /** 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 */
  11716. get: function () {
  11717. return Engine._LEQUAL;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(Engine, "GREATER", {
  11723. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11724. get: function () {
  11725. return Engine._GREATER;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine, "GEQUAL", {
  11731. /** 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 */
  11732. get: function () {
  11733. return Engine._GEQUAL;
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Engine, "NOTEQUAL", {
  11739. /** 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 */
  11740. get: function () {
  11741. return Engine._NOTEQUAL;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine, "KEEP", {
  11747. /** Passed to stencilOperation to specify that stencil value must be kept */
  11748. get: function () {
  11749. return Engine._KEEP;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Object.defineProperty(Engine, "REPLACE", {
  11755. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11756. get: function () {
  11757. return Engine._REPLACE;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine, "INCR", {
  11763. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11764. get: function () {
  11765. return Engine._INCR;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(Engine, "DECR", {
  11771. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11772. get: function () {
  11773. return Engine._DECR;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Object.defineProperty(Engine, "INVERT", {
  11779. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11780. get: function () {
  11781. return Engine._INVERT;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Engine, "INCR_WRAP", {
  11787. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11788. get: function () {
  11789. return Engine._INCR_WRAP;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine, "DECR_WRAP", {
  11795. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11796. get: function () {
  11797. return Engine._DECR_WRAP;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11803. // Alpha
  11804. /** Defines that alpha blending is disabled */
  11805. get: function () {
  11806. return Engine._ALPHA_DISABLE;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11812. /** Defines that alpha blending to SRC + DEST */
  11813. get: function () {
  11814. return Engine._ALPHA_ONEONE;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(Engine, "ALPHA_ADD", {
  11820. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11821. get: function () {
  11822. return Engine._ALPHA_ADD;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11828. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11829. get: function () {
  11830. return Engine._ALPHA_COMBINE;
  11831. },
  11832. enumerable: true,
  11833. configurable: true
  11834. });
  11835. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11836. /** Defines that alpha blending to DEST - SRC * DEST */
  11837. get: function () {
  11838. return Engine._ALPHA_SUBTRACT;
  11839. },
  11840. enumerable: true,
  11841. configurable: true
  11842. });
  11843. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11844. /** Defines that alpha blending to SRC * DEST */
  11845. get: function () {
  11846. return Engine._ALPHA_MULTIPLY;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11852. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11853. get: function () {
  11854. return Engine._ALPHA_MAXIMIZED;
  11855. },
  11856. enumerable: true,
  11857. configurable: true
  11858. });
  11859. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11860. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11861. get: function () {
  11862. return Engine._ALPHA_PREMULTIPLIED;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11868. /**
  11869. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11870. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11871. */
  11872. get: function () {
  11873. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11879. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11880. get: function () {
  11881. return Engine._ALPHA_INTERPOLATE;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11887. /**
  11888. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11889. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11890. */
  11891. get: function () {
  11892. return Engine._ALPHA_SCREENMODE;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11898. // Delays
  11899. /** Defines that the ressource is not delayed*/
  11900. get: function () {
  11901. return Engine._DELAYLOADSTATE_NONE;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11907. /** Defines that the ressource was successfully delay loaded */
  11908. get: function () {
  11909. return Engine._DELAYLOADSTATE_LOADED;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11915. /** Defines that the ressource is currently delay loading */
  11916. get: function () {
  11917. return Engine._DELAYLOADSTATE_LOADING;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11923. /** Defines that the ressource is delayed and has not started loading */
  11924. get: function () {
  11925. return Engine._DELAYLOADSTATE_NOTLOADED;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11931. /** ALPHA */
  11932. get: function () {
  11933. return Engine._TEXTUREFORMAT_ALPHA;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11939. /** LUMINANCE */
  11940. get: function () {
  11941. return Engine._TEXTUREFORMAT_LUMINANCE;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11947. /**
  11948. * R
  11949. */
  11950. get: function () {
  11951. return Engine._TEXTUREFORMAT_R;
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11957. /**
  11958. * RG
  11959. */
  11960. get: function () {
  11961. return Engine._TEXTUREFORMAT_RG;
  11962. },
  11963. enumerable: true,
  11964. configurable: true
  11965. });
  11966. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11967. /** LUMINANCE_ALPHA */
  11968. get: function () {
  11969. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11975. /** RGB */
  11976. get: function () {
  11977. return Engine._TEXTUREFORMAT_RGB;
  11978. },
  11979. enumerable: true,
  11980. configurable: true
  11981. });
  11982. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11983. /** RGBA */
  11984. get: function () {
  11985. return Engine._TEXTUREFORMAT_RGBA;
  11986. },
  11987. enumerable: true,
  11988. configurable: true
  11989. });
  11990. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11991. /** UNSIGNED_INT */
  11992. get: function () {
  11993. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11994. },
  11995. enumerable: true,
  11996. configurable: true
  11997. });
  11998. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11999. /** FLOAT */
  12000. get: function () {
  12001. return Engine._TEXTURETYPE_FLOAT;
  12002. },
  12003. enumerable: true,
  12004. configurable: true
  12005. });
  12006. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12007. /** HALF_FLOAT */
  12008. get: function () {
  12009. return Engine._TEXTURETYPE_HALF_FLOAT;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12015. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12016. get: function () {
  12017. return Engine._SCALEMODE_FLOOR;
  12018. },
  12019. enumerable: true,
  12020. configurable: true
  12021. });
  12022. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12023. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12024. get: function () {
  12025. return Engine._SCALEMODE_NEAREST;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12031. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12032. get: function () {
  12033. return Engine._SCALEMODE_CEILING;
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. Object.defineProperty(Engine, "Version", {
  12039. /**
  12040. * Returns the current version of the framework
  12041. */
  12042. get: function () {
  12043. return "3.3.0-alpha.3";
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12049. /**
  12050. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12051. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12052. */
  12053. get: function () {
  12054. return this._vrExclusivePointerMode;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12060. /**
  12061. * Gets a boolean indicating that the engine supports uniform buffers
  12062. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12063. */
  12064. get: function () {
  12065. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12071. /**
  12072. * Gets a boolean indicating that only power of 2 textures are supported
  12073. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12074. */
  12075. get: function () {
  12076. return this._webGLVersion < 2 || this.forcePOTTextures;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12082. /**
  12083. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12084. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12085. */
  12086. get: function () {
  12087. return this._doNotHandleContextLost;
  12088. },
  12089. set: function (value) {
  12090. this._doNotHandleContextLost = value;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12096. /**
  12097. * Gets the performance monitor attached to this engine
  12098. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12099. */
  12100. get: function () {
  12101. return this._performanceMonitor;
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12107. /**
  12108. * Gets the list of texture formats supported
  12109. */
  12110. get: function () {
  12111. return this._texturesSupported;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12117. /**
  12118. * Gets the list of texture formats in use
  12119. */
  12120. get: function () {
  12121. return this._textureFormatInUse;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(Engine.prototype, "currentViewport", {
  12127. /**
  12128. * Gets the current viewport
  12129. */
  12130. get: function () {
  12131. return this._cachedViewport;
  12132. },
  12133. enumerable: true,
  12134. configurable: true
  12135. });
  12136. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12137. /**
  12138. * Gets the default empty texture
  12139. */
  12140. get: function () {
  12141. if (!this._emptyTexture) {
  12142. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12143. }
  12144. return this._emptyTexture;
  12145. },
  12146. enumerable: true,
  12147. configurable: true
  12148. });
  12149. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12150. /**
  12151. * Gets the default empty 3D texture
  12152. */
  12153. get: function () {
  12154. if (!this._emptyTexture3D) {
  12155. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12156. }
  12157. return this._emptyTexture3D;
  12158. },
  12159. enumerable: true,
  12160. configurable: true
  12161. });
  12162. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12163. /**
  12164. * Gets the default empty cube texture
  12165. */
  12166. get: function () {
  12167. if (!this._emptyCubeTexture) {
  12168. var faceData = new Uint8Array(4);
  12169. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12170. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12171. }
  12172. return this._emptyCubeTexture;
  12173. },
  12174. enumerable: true,
  12175. configurable: true
  12176. });
  12177. Engine.prototype._rebuildInternalTextures = function () {
  12178. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12179. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12180. var internalTexture = currentState_1[_i];
  12181. internalTexture._rebuild();
  12182. }
  12183. };
  12184. Engine.prototype._rebuildEffects = function () {
  12185. for (var key in this._compiledEffects) {
  12186. var effect = this._compiledEffects[key];
  12187. effect._prepareEffect();
  12188. }
  12189. BABYLON.Effect.ResetCache();
  12190. };
  12191. Engine.prototype._rebuildBuffers = function () {
  12192. // Index / Vertex
  12193. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12194. var scene = _a[_i];
  12195. scene.resetCachedMaterial();
  12196. scene._rebuildGeometries();
  12197. scene._rebuildTextures();
  12198. }
  12199. // Uniforms
  12200. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12201. var uniformBuffer = _c[_b];
  12202. uniformBuffer._rebuild();
  12203. }
  12204. };
  12205. Engine.prototype._initGLContext = function () {
  12206. // Caps
  12207. this._caps = new EngineCapabilities();
  12208. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12209. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12210. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12211. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12212. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12213. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12214. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12215. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12216. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12217. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12218. // Infos
  12219. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12220. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12221. if (rendererInfo != null) {
  12222. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12223. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12224. }
  12225. if (!this._glVendor) {
  12226. this._glVendor = "Unknown vendor";
  12227. }
  12228. if (!this._glRenderer) {
  12229. this._glRenderer = "Unknown renderer";
  12230. }
  12231. // Constants
  12232. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12233. if (this._gl.RGBA16F !== 0x881A) {
  12234. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12235. }
  12236. if (this._gl.RGBA32F !== 0x8814) {
  12237. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12238. }
  12239. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12240. this._gl.DEPTH24_STENCIL8 = 35056;
  12241. }
  12242. // Extensions
  12243. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12244. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12245. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12246. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12247. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12248. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12249. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12250. 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');
  12251. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12252. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12253. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12254. this._caps.highPrecisionShaderSupported = true;
  12255. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12256. if (this._caps.timerQuery) {
  12257. if (this._webGLVersion === 1) {
  12258. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12259. }
  12260. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12261. }
  12262. // Checks if some of the format renders first to allow the use of webgl inspector.
  12263. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12264. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12265. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12266. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12267. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12268. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12269. if (this._webGLVersion > 1) {
  12270. this._gl.HALF_FLOAT_OES = 0x140B;
  12271. }
  12272. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12273. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12274. // Draw buffers
  12275. if (this._webGLVersion > 1) {
  12276. this._caps.drawBuffersExtension = true;
  12277. }
  12278. else {
  12279. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12280. if (drawBuffersExtension !== null) {
  12281. this._caps.drawBuffersExtension = true;
  12282. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12283. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12284. for (var i = 0; i < 16; i++) {
  12285. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12286. }
  12287. }
  12288. else {
  12289. this._caps.drawBuffersExtension = false;
  12290. }
  12291. }
  12292. // Depth Texture
  12293. if (this._webGLVersion > 1) {
  12294. this._caps.depthTextureExtension = true;
  12295. }
  12296. else {
  12297. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12298. if (depthTextureExtension != null) {
  12299. this._caps.depthTextureExtension = true;
  12300. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12301. }
  12302. }
  12303. // Vertex array object
  12304. if (this._webGLVersion > 1) {
  12305. this._caps.vertexArrayObject = true;
  12306. }
  12307. else {
  12308. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12309. if (vertexArrayObjectExtension != null) {
  12310. this._caps.vertexArrayObject = true;
  12311. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12312. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12313. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12314. }
  12315. else {
  12316. this._caps.vertexArrayObject = false;
  12317. }
  12318. }
  12319. // Instances count
  12320. if (this._webGLVersion > 1) {
  12321. this._caps.instancedArrays = true;
  12322. }
  12323. else {
  12324. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12325. if (instanceExtension != null) {
  12326. this._caps.instancedArrays = true;
  12327. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12328. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12329. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12330. }
  12331. else {
  12332. this._caps.instancedArrays = false;
  12333. }
  12334. }
  12335. // Intelligently add supported compressed formats in order to check for.
  12336. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12337. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12338. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12339. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12340. if (this._caps.astc)
  12341. this.texturesSupported.push('-astc.ktx');
  12342. if (this._caps.s3tc)
  12343. this.texturesSupported.push('-dxt.ktx');
  12344. if (this._caps.pvrtc)
  12345. this.texturesSupported.push('-pvrtc.ktx');
  12346. if (this._caps.etc2)
  12347. this.texturesSupported.push('-etc2.ktx');
  12348. if (this._caps.etc1)
  12349. this.texturesSupported.push('-etc1.ktx');
  12350. if (this._gl.getShaderPrecisionFormat) {
  12351. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12352. if (highp) {
  12353. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12354. }
  12355. }
  12356. // Depth buffer
  12357. this.setDepthBuffer(true);
  12358. this.setDepthFunctionToLessOrEqual();
  12359. this.setDepthWrite(true);
  12360. // Texture maps
  12361. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12362. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12363. this._nextFreeTextureSlots.push(slot);
  12364. }
  12365. };
  12366. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12367. /**
  12368. * Gets version of the current webGL context
  12369. */
  12370. get: function () {
  12371. return this._webGLVersion;
  12372. },
  12373. enumerable: true,
  12374. configurable: true
  12375. });
  12376. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12377. /**
  12378. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12379. */
  12380. get: function () {
  12381. return this._isStencilEnable;
  12382. },
  12383. enumerable: true,
  12384. configurable: true
  12385. });
  12386. Engine.prototype._prepareWorkingCanvas = function () {
  12387. if (this._workingCanvas) {
  12388. return;
  12389. }
  12390. this._workingCanvas = document.createElement("canvas");
  12391. var context = this._workingCanvas.getContext("2d");
  12392. if (context) {
  12393. this._workingContext = context;
  12394. }
  12395. };
  12396. /**
  12397. * Reset the texture cache to empty state
  12398. */
  12399. Engine.prototype.resetTextureCache = function () {
  12400. for (var key in this._boundTexturesCache) {
  12401. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12402. continue;
  12403. }
  12404. var boundTexture = this._boundTexturesCache[key];
  12405. if (boundTexture) {
  12406. this._removeDesignatedSlot(boundTexture);
  12407. }
  12408. this._boundTexturesCache[key] = null;
  12409. }
  12410. if (!this.disableTextureBindingOptimization) {
  12411. this._nextFreeTextureSlots = [];
  12412. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12413. this._nextFreeTextureSlots.push(slot);
  12414. }
  12415. }
  12416. this._currentTextureChannel = -1;
  12417. };
  12418. /**
  12419. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12420. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12421. * @returns true if engine is in deterministic lock step mode
  12422. */
  12423. Engine.prototype.isDeterministicLockStep = function () {
  12424. return this._deterministicLockstep;
  12425. };
  12426. /**
  12427. * Gets the max steps when engine is running in deterministic lock step
  12428. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12429. * @returns the max steps
  12430. */
  12431. Engine.prototype.getLockstepMaxSteps = function () {
  12432. return this._lockstepMaxSteps;
  12433. };
  12434. /**
  12435. * Gets an object containing information about the current webGL context
  12436. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12437. */
  12438. Engine.prototype.getGlInfo = function () {
  12439. return {
  12440. vendor: this._glVendor,
  12441. renderer: this._glRenderer,
  12442. version: this._glVersion
  12443. };
  12444. };
  12445. /**
  12446. * Gets current aspect ratio
  12447. * @param camera defines the camera to use to get the aspect ratio
  12448. * @param useScreen defines if screen size must be used (or the current render target if any)
  12449. * @returns a number defining the aspect ratio
  12450. */
  12451. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12452. if (useScreen === void 0) { useScreen = false; }
  12453. var viewport = camera.viewport;
  12454. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12455. };
  12456. /**
  12457. * Gets current screen aspect ratio
  12458. * @returns a number defining the aspect ratio
  12459. */
  12460. Engine.prototype.getScreenAspectRatio = function () {
  12461. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12462. };
  12463. /**
  12464. * Gets the current render width
  12465. * @param useScreen defines if screen size must be used (or the current render target if any)
  12466. * @returns a number defining the current render width
  12467. */
  12468. Engine.prototype.getRenderWidth = function (useScreen) {
  12469. if (useScreen === void 0) { useScreen = false; }
  12470. if (!useScreen && this._currentRenderTarget) {
  12471. return this._currentRenderTarget.width;
  12472. }
  12473. return this._gl.drawingBufferWidth;
  12474. };
  12475. /**
  12476. * Gets the current render height
  12477. * @param useScreen defines if screen size must be used (or the current render target if any)
  12478. * @returns a number defining the current render height
  12479. */
  12480. Engine.prototype.getRenderHeight = function (useScreen) {
  12481. if (useScreen === void 0) { useScreen = false; }
  12482. if (!useScreen && this._currentRenderTarget) {
  12483. return this._currentRenderTarget.height;
  12484. }
  12485. return this._gl.drawingBufferHeight;
  12486. };
  12487. /**
  12488. * Gets the HTML canvas attached with the current webGL context
  12489. * @returns a HTML canvas
  12490. */
  12491. Engine.prototype.getRenderingCanvas = function () {
  12492. return this._renderingCanvas;
  12493. };
  12494. /**
  12495. * Gets the client rect of the HTML canvas attached with the current webGL context
  12496. * @returns a client rectanglee
  12497. */
  12498. Engine.prototype.getRenderingCanvasClientRect = function () {
  12499. if (!this._renderingCanvas) {
  12500. return null;
  12501. }
  12502. return this._renderingCanvas.getBoundingClientRect();
  12503. };
  12504. /**
  12505. * Defines the hardware scaling level.
  12506. * By default the hardware scaling level is computed from the window device ratio.
  12507. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12508. * @param level defines the level to use
  12509. */
  12510. Engine.prototype.setHardwareScalingLevel = function (level) {
  12511. this._hardwareScalingLevel = level;
  12512. this.resize();
  12513. };
  12514. /**
  12515. * Gets the current hardware scaling level.
  12516. * By default the hardware scaling level is computed from the window device ratio.
  12517. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12518. * @returns a number indicating the current hardware scaling level
  12519. */
  12520. Engine.prototype.getHardwareScalingLevel = function () {
  12521. return this._hardwareScalingLevel;
  12522. };
  12523. /**
  12524. * Gets the list of loaded textures
  12525. * @returns an array containing all loaded textures
  12526. */
  12527. Engine.prototype.getLoadedTexturesCache = function () {
  12528. return this._internalTexturesCache;
  12529. };
  12530. /**
  12531. * Gets the object containing all engine capabilities
  12532. * @returns the EngineCapabilities object
  12533. */
  12534. Engine.prototype.getCaps = function () {
  12535. return this._caps;
  12536. };
  12537. Object.defineProperty(Engine.prototype, "drawCalls", {
  12538. /** @hidden */
  12539. get: function () {
  12540. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12541. return 0;
  12542. },
  12543. enumerable: true,
  12544. configurable: true
  12545. });
  12546. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12547. /** @hidden */
  12548. get: function () {
  12549. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12550. return null;
  12551. },
  12552. enumerable: true,
  12553. configurable: true
  12554. });
  12555. /**
  12556. * Gets the current depth function
  12557. * @returns a number defining the depth function
  12558. */
  12559. Engine.prototype.getDepthFunction = function () {
  12560. return this._depthCullingState.depthFunc;
  12561. };
  12562. /**
  12563. * Sets the current depth function
  12564. * @param depthFunc defines the function to use
  12565. */
  12566. Engine.prototype.setDepthFunction = function (depthFunc) {
  12567. this._depthCullingState.depthFunc = depthFunc;
  12568. };
  12569. /**
  12570. * Sets the current depth function to GREATER
  12571. */
  12572. Engine.prototype.setDepthFunctionToGreater = function () {
  12573. this._depthCullingState.depthFunc = this._gl.GREATER;
  12574. };
  12575. /**
  12576. * Sets the current depth function to GEQUAL
  12577. */
  12578. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12579. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12580. };
  12581. /**
  12582. * Sets the current depth function to LESS
  12583. */
  12584. Engine.prototype.setDepthFunctionToLess = function () {
  12585. this._depthCullingState.depthFunc = this._gl.LESS;
  12586. };
  12587. /**
  12588. * Sets the current depth function to LEQUAL
  12589. */
  12590. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12591. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12592. };
  12593. /**
  12594. * Gets a boolean indicating if stencil buffer is enabled
  12595. * @returns the current stencil buffer state
  12596. */
  12597. Engine.prototype.getStencilBuffer = function () {
  12598. return this._stencilState.stencilTest;
  12599. };
  12600. /**
  12601. * Enable or disable the stencil buffer
  12602. * @param enable defines if the stencil buffer must be enabled or disabled
  12603. */
  12604. Engine.prototype.setStencilBuffer = function (enable) {
  12605. this._stencilState.stencilTest = enable;
  12606. };
  12607. /**
  12608. * Gets the current stencil mask
  12609. * @returns a number defining the new stencil mask to use
  12610. */
  12611. Engine.prototype.getStencilMask = function () {
  12612. return this._stencilState.stencilMask;
  12613. };
  12614. /**
  12615. * Sets the current stencil mask
  12616. * @param mask defines the new stencil mask to use
  12617. */
  12618. Engine.prototype.setStencilMask = function (mask) {
  12619. this._stencilState.stencilMask = mask;
  12620. };
  12621. /**
  12622. * Gets the current stencil function
  12623. * @returns a number defining the stencil function to use
  12624. */
  12625. Engine.prototype.getStencilFunction = function () {
  12626. return this._stencilState.stencilFunc;
  12627. };
  12628. /**
  12629. * Gets the current stencil reference value
  12630. * @returns a number defining the stencil reference value to use
  12631. */
  12632. Engine.prototype.getStencilFunctionReference = function () {
  12633. return this._stencilState.stencilFuncRef;
  12634. };
  12635. /**
  12636. * Gets the current stencil mask
  12637. * @returns a number defining the stencil mask to use
  12638. */
  12639. Engine.prototype.getStencilFunctionMask = function () {
  12640. return this._stencilState.stencilFuncMask;
  12641. };
  12642. /**
  12643. * Sets the current stencil function
  12644. * @param stencilFunc defines the new stencil function to use
  12645. */
  12646. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12647. this._stencilState.stencilFunc = stencilFunc;
  12648. };
  12649. /**
  12650. * Sets the current stencil reference
  12651. * @param reference defines the new stencil reference to use
  12652. */
  12653. Engine.prototype.setStencilFunctionReference = function (reference) {
  12654. this._stencilState.stencilFuncRef = reference;
  12655. };
  12656. /**
  12657. * Sets the current stencil mask
  12658. * @param mask defines the new stencil mask to use
  12659. */
  12660. Engine.prototype.setStencilFunctionMask = function (mask) {
  12661. this._stencilState.stencilFuncMask = mask;
  12662. };
  12663. /**
  12664. * Gets the current stencil operation when stencil fails
  12665. * @returns a number defining stencil operation to use when stencil fails
  12666. */
  12667. Engine.prototype.getStencilOperationFail = function () {
  12668. return this._stencilState.stencilOpStencilFail;
  12669. };
  12670. /**
  12671. * Gets the current stencil operation when depth fails
  12672. * @returns a number defining stencil operation to use when depth fails
  12673. */
  12674. Engine.prototype.getStencilOperationDepthFail = function () {
  12675. return this._stencilState.stencilOpDepthFail;
  12676. };
  12677. /**
  12678. * Gets the current stencil operation when stencil passes
  12679. * @returns a number defining stencil operation to use when stencil passes
  12680. */
  12681. Engine.prototype.getStencilOperationPass = function () {
  12682. return this._stencilState.stencilOpStencilDepthPass;
  12683. };
  12684. /**
  12685. * Sets the stencil operation to use when stencil fails
  12686. * @param operation defines the stencil operation to use when stencil fails
  12687. */
  12688. Engine.prototype.setStencilOperationFail = function (operation) {
  12689. this._stencilState.stencilOpStencilFail = operation;
  12690. };
  12691. /**
  12692. * Sets the stencil operation to use when depth fails
  12693. * @param operation defines the stencil operation to use when depth fails
  12694. */
  12695. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12696. this._stencilState.stencilOpDepthFail = operation;
  12697. };
  12698. /**
  12699. * Sets the stencil operation to use when stencil passes
  12700. * @param operation defines the stencil operation to use when stencil passes
  12701. */
  12702. Engine.prototype.setStencilOperationPass = function (operation) {
  12703. this._stencilState.stencilOpStencilDepthPass = operation;
  12704. };
  12705. /**
  12706. * Sets a boolean indicating if the dithering state is enabled or disabled
  12707. * @param value defines the dithering state
  12708. */
  12709. Engine.prototype.setDitheringState = function (value) {
  12710. if (value) {
  12711. this._gl.enable(this._gl.DITHER);
  12712. }
  12713. else {
  12714. this._gl.disable(this._gl.DITHER);
  12715. }
  12716. };
  12717. /**
  12718. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12719. * @param value defines the rasterizer state
  12720. */
  12721. Engine.prototype.setRasterizerState = function (value) {
  12722. if (value) {
  12723. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12724. }
  12725. else {
  12726. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12727. }
  12728. };
  12729. /**
  12730. * stop executing a render loop function and remove it from the execution array
  12731. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12732. */
  12733. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12734. if (!renderFunction) {
  12735. this._activeRenderLoops = [];
  12736. return;
  12737. }
  12738. var index = this._activeRenderLoops.indexOf(renderFunction);
  12739. if (index >= 0) {
  12740. this._activeRenderLoops.splice(index, 1);
  12741. }
  12742. };
  12743. /** @hidden */
  12744. Engine.prototype._renderLoop = function () {
  12745. if (!this._contextWasLost) {
  12746. var shouldRender = true;
  12747. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12748. shouldRender = false;
  12749. }
  12750. if (shouldRender) {
  12751. // Start new frame
  12752. this.beginFrame();
  12753. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12754. var renderFunction = this._activeRenderLoops[index];
  12755. renderFunction();
  12756. }
  12757. // Present
  12758. this.endFrame();
  12759. }
  12760. }
  12761. if (this._activeRenderLoops.length > 0) {
  12762. // Register new frame
  12763. var requester = null;
  12764. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12765. requester = this._vrDisplay;
  12766. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12767. }
  12768. else {
  12769. this._renderingQueueLaunched = false;
  12770. }
  12771. };
  12772. /**
  12773. * Register and execute a render loop. The engine can have more than one render function
  12774. * @param renderFunction defines the function to continuously execute
  12775. */
  12776. Engine.prototype.runRenderLoop = function (renderFunction) {
  12777. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12778. return;
  12779. }
  12780. this._activeRenderLoops.push(renderFunction);
  12781. if (!this._renderingQueueLaunched) {
  12782. this._renderingQueueLaunched = true;
  12783. this._bindedRenderFunction = this._renderLoop.bind(this);
  12784. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12785. }
  12786. };
  12787. /**
  12788. * Toggle full screen mode
  12789. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12790. * @param options defines an option object to be sent to the requestFullscreen function
  12791. */
  12792. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12793. if (this.isFullscreen) {
  12794. BABYLON.Tools.ExitFullscreen();
  12795. }
  12796. else {
  12797. this._pointerLockRequested = requestPointerLock;
  12798. if (this._renderingCanvas) {
  12799. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12800. }
  12801. }
  12802. };
  12803. /**
  12804. * Clear the current render buffer or the current render target (if any is set up)
  12805. * @param color defines the color to use
  12806. * @param backBuffer defines if the back buffer must be cleared
  12807. * @param depth defines if the depth buffer must be cleared
  12808. * @param stencil defines if the stencil buffer must be cleared
  12809. */
  12810. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12811. if (stencil === void 0) { stencil = false; }
  12812. this.applyStates();
  12813. var mode = 0;
  12814. if (backBuffer && color) {
  12815. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12816. mode |= this._gl.COLOR_BUFFER_BIT;
  12817. }
  12818. if (depth) {
  12819. this._gl.clearDepth(1.0);
  12820. mode |= this._gl.DEPTH_BUFFER_BIT;
  12821. }
  12822. if (stencil) {
  12823. this._gl.clearStencil(0);
  12824. mode |= this._gl.STENCIL_BUFFER_BIT;
  12825. }
  12826. this._gl.clear(mode);
  12827. };
  12828. /**
  12829. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12830. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12831. * @param y defines the y-coordinate of the corner of the clear rectangle
  12832. * @param width defines the width of the clear rectangle
  12833. * @param height defines the height of the clear rectangle
  12834. * @param clearColor defines the clear color
  12835. */
  12836. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12837. var gl = this._gl;
  12838. // Save state
  12839. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12840. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12841. // Change state
  12842. gl.enable(gl.SCISSOR_TEST);
  12843. gl.scissor(x, y, width, height);
  12844. // Clear
  12845. this.clear(clearColor, true, true, true);
  12846. // Restore state
  12847. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12848. if (curScissor === true) {
  12849. gl.enable(gl.SCISSOR_TEST);
  12850. }
  12851. else {
  12852. gl.disable(gl.SCISSOR_TEST);
  12853. }
  12854. };
  12855. /**
  12856. * Set the WebGL's viewport
  12857. * @param viewport defines the viewport element to be used
  12858. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12859. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12860. */
  12861. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12862. var width = requiredWidth || this.getRenderWidth();
  12863. var height = requiredHeight || this.getRenderHeight();
  12864. var x = viewport.x || 0;
  12865. var y = viewport.y || 0;
  12866. this._cachedViewport = viewport;
  12867. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12868. };
  12869. /**
  12870. * Directly set the WebGL Viewport
  12871. * @param x defines the x coordinate of the viewport (in screen space)
  12872. * @param y defines the y coordinate of the viewport (in screen space)
  12873. * @param width defines the width of the viewport (in screen space)
  12874. * @param height defines the height of the viewport (in screen space)
  12875. * @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
  12876. */
  12877. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12878. var currentViewport = this._cachedViewport;
  12879. this._cachedViewport = null;
  12880. this._gl.viewport(x, y, width, height);
  12881. return currentViewport;
  12882. };
  12883. /**
  12884. * Begin a new frame
  12885. */
  12886. Engine.prototype.beginFrame = function () {
  12887. this.onBeginFrameObservable.notifyObservers(this);
  12888. this._measureFps();
  12889. };
  12890. /**
  12891. * Enf the current frame
  12892. */
  12893. Engine.prototype.endFrame = function () {
  12894. // Force a flush in case we are using a bad OS.
  12895. if (this._badOS) {
  12896. this.flushFramebuffer();
  12897. }
  12898. // Submit frame to the vr device, if enabled
  12899. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12900. // TODO: We should only submit the frame if we read frameData successfully.
  12901. this._vrDisplay.submitFrame();
  12902. }
  12903. this.onEndFrameObservable.notifyObservers(this);
  12904. };
  12905. /**
  12906. * Resize the view according to the canvas' size
  12907. */
  12908. Engine.prototype.resize = function () {
  12909. // We're not resizing the size of the canvas while in VR mode & presenting
  12910. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12911. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12912. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12913. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12914. }
  12915. };
  12916. /**
  12917. * Force a specific size of the canvas
  12918. * @param width defines the new canvas' width
  12919. * @param height defines the new canvas' height
  12920. */
  12921. Engine.prototype.setSize = function (width, height) {
  12922. if (!this._renderingCanvas) {
  12923. return;
  12924. }
  12925. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12926. return;
  12927. }
  12928. this._renderingCanvas.width = width;
  12929. this._renderingCanvas.height = height;
  12930. for (var index = 0; index < this.scenes.length; index++) {
  12931. var scene = this.scenes[index];
  12932. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12933. var cam = scene.cameras[camIndex];
  12934. cam._currentRenderId = 0;
  12935. }
  12936. }
  12937. if (this.onResizeObservable.hasObservers) {
  12938. this.onResizeObservable.notifyObservers(this);
  12939. }
  12940. };
  12941. // WebVR functions
  12942. /**
  12943. * Gets a boolean indicating if a webVR device was detected
  12944. * @returns true if a webVR device was detected
  12945. */
  12946. Engine.prototype.isVRDevicePresent = function () {
  12947. return !!this._vrDisplay;
  12948. };
  12949. /**
  12950. * Gets the current webVR device
  12951. * @returns the current webVR device (or null)
  12952. */
  12953. Engine.prototype.getVRDevice = function () {
  12954. return this._vrDisplay;
  12955. };
  12956. /**
  12957. * Initializes a webVR display and starts listening to display change events
  12958. * The onVRDisplayChangedObservable will be notified upon these changes
  12959. * @returns The onVRDisplayChangedObservable
  12960. */
  12961. Engine.prototype.initWebVR = function () {
  12962. this.initWebVRAsync();
  12963. return this.onVRDisplayChangedObservable;
  12964. };
  12965. /**
  12966. * Initializes a webVR display and starts listening to display change events
  12967. * The onVRDisplayChangedObservable will be notified upon these changes
  12968. * @returns A promise containing a VRDisplay and if vr is supported
  12969. */
  12970. Engine.prototype.initWebVRAsync = function () {
  12971. var _this = this;
  12972. var notifyObservers = function () {
  12973. var eventArgs = {
  12974. vrDisplay: _this._vrDisplay,
  12975. vrSupported: _this._vrSupported
  12976. };
  12977. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12978. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12979. };
  12980. if (!this._onVrDisplayConnect) {
  12981. this._onVrDisplayConnect = function (event) {
  12982. _this._vrDisplay = event.display;
  12983. notifyObservers();
  12984. };
  12985. this._onVrDisplayDisconnect = function () {
  12986. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12987. _this._vrDisplay = undefined;
  12988. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12989. notifyObservers();
  12990. };
  12991. this._onVrDisplayPresentChange = function () {
  12992. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12993. };
  12994. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12995. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12996. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12997. }
  12998. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12999. this._webVRInitPromise.then(notifyObservers);
  13000. return this._webVRInitPromise;
  13001. };
  13002. /**
  13003. * Call this function to switch to webVR mode
  13004. * Will do nothing if webVR is not supported or if there is no webVR device
  13005. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13006. */
  13007. Engine.prototype.enableVR = function () {
  13008. var _this = this;
  13009. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13010. var onResolved = function () {
  13011. _this.onVRRequestPresentComplete.notifyObservers(true);
  13012. _this._onVRFullScreenTriggered();
  13013. };
  13014. var onRejected = function () {
  13015. _this.onVRRequestPresentComplete.notifyObservers(false);
  13016. };
  13017. this.onVRRequestPresentStart.notifyObservers(this);
  13018. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13019. }
  13020. };
  13021. /**
  13022. * Call this function to leave webVR mode
  13023. * Will do nothing if webVR is not supported or if there is no webVR device
  13024. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13025. */
  13026. Engine.prototype.disableVR = function () {
  13027. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13028. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13029. }
  13030. };
  13031. Engine.prototype._getVRDisplaysAsync = function () {
  13032. var _this = this;
  13033. return new Promise(function (res, rej) {
  13034. if (navigator.getVRDisplays) {
  13035. navigator.getVRDisplays().then(function (devices) {
  13036. _this._vrSupported = true;
  13037. // note that devices may actually be an empty array. This is fine;
  13038. // we expect this._vrDisplay to be undefined in this case.
  13039. _this._vrDisplay = devices[0];
  13040. res({
  13041. vrDisplay: _this._vrDisplay,
  13042. vrSupported: _this._vrSupported
  13043. });
  13044. });
  13045. }
  13046. else {
  13047. _this._vrDisplay = undefined;
  13048. _this._vrSupported = false;
  13049. res({
  13050. vrDisplay: _this._vrDisplay,
  13051. vrSupported: _this._vrSupported
  13052. });
  13053. }
  13054. });
  13055. };
  13056. /**
  13057. * Binds the frame buffer to the specified texture.
  13058. * @param texture The texture to render to or null for the default canvas
  13059. * @param faceIndex The face of the texture to render to in case of cube texture
  13060. * @param requiredWidth The width of the target to render to
  13061. * @param requiredHeight The height of the target to render to
  13062. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13063. * @param depthStencilTexture The depth stencil texture to use to render
  13064. * @param lodLevel defines le lod level to bind to the frame buffer
  13065. */
  13066. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13067. if (lodLevel === void 0) { lodLevel = 0; }
  13068. if (this._currentRenderTarget) {
  13069. this.unBindFramebuffer(this._currentRenderTarget);
  13070. }
  13071. this._currentRenderTarget = texture;
  13072. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13073. var gl = this._gl;
  13074. if (texture.isCube) {
  13075. if (faceIndex === undefined) {
  13076. faceIndex = 0;
  13077. }
  13078. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13079. if (depthStencilTexture) {
  13080. if (depthStencilTexture._generateStencilBuffer) {
  13081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13082. }
  13083. else {
  13084. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13085. }
  13086. }
  13087. }
  13088. if (this._cachedViewport && !forceFullscreenViewport) {
  13089. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13090. }
  13091. else {
  13092. if (!requiredWidth) {
  13093. requiredWidth = texture.width;
  13094. if (lodLevel) {
  13095. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13096. }
  13097. }
  13098. if (!requiredHeight) {
  13099. requiredHeight = texture.height;
  13100. if (lodLevel) {
  13101. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13102. }
  13103. }
  13104. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13105. }
  13106. this.wipeCaches();
  13107. };
  13108. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13109. if (this._currentFramebuffer !== framebuffer) {
  13110. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13111. this._currentFramebuffer = framebuffer;
  13112. }
  13113. };
  13114. /**
  13115. * Unbind the current render target texture from the webGL context
  13116. * @param texture defines the render target texture to unbind
  13117. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13118. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13119. */
  13120. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13121. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13122. this._currentRenderTarget = null;
  13123. // If MSAA, we need to bitblt back to main texture
  13124. var gl = this._gl;
  13125. if (texture._MSAAFramebuffer) {
  13126. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13127. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13128. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13129. }
  13130. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13131. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13132. gl.generateMipmap(gl.TEXTURE_2D);
  13133. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13134. }
  13135. if (onBeforeUnbind) {
  13136. if (texture._MSAAFramebuffer) {
  13137. // Bind the correct framebuffer
  13138. this.bindUnboundFramebuffer(texture._framebuffer);
  13139. }
  13140. onBeforeUnbind();
  13141. }
  13142. this.bindUnboundFramebuffer(null);
  13143. };
  13144. /**
  13145. * Unbind a list of render target textures from the webGL context
  13146. * This is used only when drawBuffer extension or webGL2 are active
  13147. * @param textures defines the render target textures to unbind
  13148. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13149. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13150. */
  13151. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13152. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13153. this._currentRenderTarget = null;
  13154. // If MSAA, we need to bitblt back to main texture
  13155. var gl = this._gl;
  13156. if (textures[0]._MSAAFramebuffer) {
  13157. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13158. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13159. var attachments = textures[0]._attachments;
  13160. if (!attachments) {
  13161. attachments = new Array(textures.length);
  13162. textures[0]._attachments = attachments;
  13163. }
  13164. for (var i = 0; i < textures.length; i++) {
  13165. var texture = textures[i];
  13166. for (var j = 0; j < attachments.length; j++) {
  13167. attachments[j] = gl.NONE;
  13168. }
  13169. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13170. gl.readBuffer(attachments[i]);
  13171. gl.drawBuffers(attachments);
  13172. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13173. }
  13174. for (var i = 0; i < attachments.length; i++) {
  13175. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13176. }
  13177. gl.drawBuffers(attachments);
  13178. }
  13179. for (var i = 0; i < textures.length; i++) {
  13180. var texture = textures[i];
  13181. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13182. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13183. gl.generateMipmap(gl.TEXTURE_2D);
  13184. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13185. }
  13186. }
  13187. if (onBeforeUnbind) {
  13188. if (textures[0]._MSAAFramebuffer) {
  13189. // Bind the correct framebuffer
  13190. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13191. }
  13192. onBeforeUnbind();
  13193. }
  13194. this.bindUnboundFramebuffer(null);
  13195. };
  13196. /**
  13197. * Force the mipmap generation for the given render target texture
  13198. * @param texture defines the render target texture to use
  13199. */
  13200. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13201. if (texture.generateMipMaps) {
  13202. var gl = this._gl;
  13203. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13204. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13205. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13206. }
  13207. };
  13208. /**
  13209. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13210. */
  13211. Engine.prototype.flushFramebuffer = function () {
  13212. this._gl.flush();
  13213. };
  13214. /**
  13215. * Unbind the current render target and bind the default framebuffer
  13216. */
  13217. Engine.prototype.restoreDefaultFramebuffer = function () {
  13218. if (this._currentRenderTarget) {
  13219. this.unBindFramebuffer(this._currentRenderTarget);
  13220. }
  13221. else {
  13222. this.bindUnboundFramebuffer(null);
  13223. }
  13224. if (this._cachedViewport) {
  13225. this.setViewport(this._cachedViewport);
  13226. }
  13227. this.wipeCaches();
  13228. };
  13229. // UBOs
  13230. /**
  13231. * Create an uniform buffer
  13232. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13233. * @param elements defines the content of the uniform buffer
  13234. * @returns the webGL uniform buffer
  13235. */
  13236. Engine.prototype.createUniformBuffer = function (elements) {
  13237. var ubo = this._gl.createBuffer();
  13238. if (!ubo) {
  13239. throw new Error("Unable to create uniform buffer");
  13240. }
  13241. this.bindUniformBuffer(ubo);
  13242. if (elements instanceof Float32Array) {
  13243. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13244. }
  13245. else {
  13246. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13247. }
  13248. this.bindUniformBuffer(null);
  13249. ubo.references = 1;
  13250. return ubo;
  13251. };
  13252. /**
  13253. * Create a dynamic uniform buffer
  13254. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13255. * @param elements defines the content of the uniform buffer
  13256. * @returns the webGL uniform buffer
  13257. */
  13258. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13259. var ubo = this._gl.createBuffer();
  13260. if (!ubo) {
  13261. throw new Error("Unable to create dynamic uniform buffer");
  13262. }
  13263. this.bindUniformBuffer(ubo);
  13264. if (elements instanceof Float32Array) {
  13265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13266. }
  13267. else {
  13268. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13269. }
  13270. this.bindUniformBuffer(null);
  13271. ubo.references = 1;
  13272. return ubo;
  13273. };
  13274. /**
  13275. * Update an existing uniform buffer
  13276. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13277. * @param uniformBuffer defines the target uniform buffer
  13278. * @param elements defines the content to update
  13279. * @param offset defines the offset in the uniform buffer where update should start
  13280. * @param count defines the size of the data to update
  13281. */
  13282. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13283. this.bindUniformBuffer(uniformBuffer);
  13284. if (offset === undefined) {
  13285. offset = 0;
  13286. }
  13287. if (count === undefined) {
  13288. if (elements instanceof Float32Array) {
  13289. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13290. }
  13291. else {
  13292. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13293. }
  13294. }
  13295. else {
  13296. if (elements instanceof Float32Array) {
  13297. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13298. }
  13299. else {
  13300. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13301. }
  13302. }
  13303. this.bindUniformBuffer(null);
  13304. };
  13305. // VBOs
  13306. Engine.prototype._resetVertexBufferBinding = function () {
  13307. this.bindArrayBuffer(null);
  13308. this._cachedVertexBuffers = null;
  13309. };
  13310. /**
  13311. * Creates a vertex buffer
  13312. * @param data the data for the vertex buffer
  13313. * @returns the new WebGL static buffer
  13314. */
  13315. Engine.prototype.createVertexBuffer = function (data) {
  13316. var vbo = this._gl.createBuffer();
  13317. if (!vbo) {
  13318. throw new Error("Unable to create vertex buffer");
  13319. }
  13320. this.bindArrayBuffer(vbo);
  13321. if (data instanceof Array) {
  13322. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13323. }
  13324. else {
  13325. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13326. }
  13327. this._resetVertexBufferBinding();
  13328. vbo.references = 1;
  13329. return vbo;
  13330. };
  13331. /**
  13332. * Creates a dynamic vertex buffer
  13333. * @param data the data for the dynamic vertex buffer
  13334. * @returns the new WebGL dynamic buffer
  13335. */
  13336. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13337. var vbo = this._gl.createBuffer();
  13338. if (!vbo) {
  13339. throw new Error("Unable to create dynamic vertex buffer");
  13340. }
  13341. this.bindArrayBuffer(vbo);
  13342. if (data instanceof Array) {
  13343. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13344. }
  13345. else {
  13346. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13347. }
  13348. this._resetVertexBufferBinding();
  13349. vbo.references = 1;
  13350. return vbo;
  13351. };
  13352. /**
  13353. * Update a dynamic index buffer
  13354. * @param indexBuffer defines the target index buffer
  13355. * @param indices defines the data to update
  13356. * @param offset defines the offset in the target index buffer where update should start
  13357. */
  13358. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13359. if (offset === void 0) { offset = 0; }
  13360. // Force cache update
  13361. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13362. this.bindIndexBuffer(indexBuffer);
  13363. var arrayBuffer;
  13364. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13365. arrayBuffer = indices;
  13366. }
  13367. else {
  13368. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13369. }
  13370. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13371. this._resetIndexBufferBinding();
  13372. };
  13373. /**
  13374. * Updates a dynamic vertex buffer.
  13375. * @param vertexBuffer the vertex buffer to update
  13376. * @param data the data used to update the vertex buffer
  13377. * @param byteOffset the byte offset of the data
  13378. * @param byteLength the byte length of the data
  13379. */
  13380. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13381. this.bindArrayBuffer(vertexBuffer);
  13382. if (byteOffset === undefined) {
  13383. byteOffset = 0;
  13384. }
  13385. if (byteLength === undefined) {
  13386. if (data instanceof Array) {
  13387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13388. }
  13389. else {
  13390. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13391. }
  13392. }
  13393. else {
  13394. if (data instanceof Array) {
  13395. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13396. }
  13397. else {
  13398. if (data instanceof ArrayBuffer) {
  13399. data = new Uint8Array(data, byteOffset, byteLength);
  13400. }
  13401. else {
  13402. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13403. }
  13404. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13405. }
  13406. }
  13407. this._resetVertexBufferBinding();
  13408. };
  13409. Engine.prototype._resetIndexBufferBinding = function () {
  13410. this.bindIndexBuffer(null);
  13411. this._cachedIndexBuffer = null;
  13412. };
  13413. /**
  13414. * Creates a new index buffer
  13415. * @param indices defines the content of the index buffer
  13416. * @param updatable defines if the index buffer must be updatable
  13417. * @returns a new webGL buffer
  13418. */
  13419. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13420. var vbo = this._gl.createBuffer();
  13421. if (!vbo) {
  13422. throw new Error("Unable to create index buffer");
  13423. }
  13424. this.bindIndexBuffer(vbo);
  13425. // Check for 32 bits indices
  13426. var arrayBuffer;
  13427. var need32Bits = false;
  13428. if (indices instanceof Uint16Array) {
  13429. arrayBuffer = indices;
  13430. }
  13431. else {
  13432. //check 32 bit support
  13433. if (this._caps.uintIndices) {
  13434. if (indices instanceof Uint32Array) {
  13435. arrayBuffer = indices;
  13436. need32Bits = true;
  13437. }
  13438. else {
  13439. //number[] or Int32Array, check if 32 bit is necessary
  13440. for (var index = 0; index < indices.length; index++) {
  13441. if (indices[index] > 65535) {
  13442. need32Bits = true;
  13443. break;
  13444. }
  13445. }
  13446. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13447. }
  13448. }
  13449. else {
  13450. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13451. arrayBuffer = new Uint16Array(indices);
  13452. }
  13453. }
  13454. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13455. this._resetIndexBufferBinding();
  13456. vbo.references = 1;
  13457. vbo.is32Bits = need32Bits;
  13458. return vbo;
  13459. };
  13460. /**
  13461. * Bind a webGL buffer to the webGL context
  13462. * @param buffer defines the buffer to bind
  13463. */
  13464. Engine.prototype.bindArrayBuffer = function (buffer) {
  13465. if (!this._vaoRecordInProgress) {
  13466. this._unbindVertexArrayObject();
  13467. }
  13468. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13469. };
  13470. /**
  13471. * Bind an uniform buffer to the current webGL context
  13472. * @param buffer defines the buffer to bind
  13473. */
  13474. Engine.prototype.bindUniformBuffer = function (buffer) {
  13475. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13476. };
  13477. /**
  13478. * Bind a buffer to the current webGL context at a given location
  13479. * @param buffer defines the buffer to bind
  13480. * @param location defines the index where to bind the buffer
  13481. */
  13482. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13483. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13484. };
  13485. /**
  13486. * Bind a specific block at a given index in a specific shader program
  13487. * @param shaderProgram defines the shader program
  13488. * @param blockName defines the block name
  13489. * @param index defines the index where to bind the block
  13490. */
  13491. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13492. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13493. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13494. };
  13495. ;
  13496. Engine.prototype.bindIndexBuffer = function (buffer) {
  13497. if (!this._vaoRecordInProgress) {
  13498. this._unbindVertexArrayObject();
  13499. }
  13500. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13501. };
  13502. Engine.prototype.bindBuffer = function (buffer, target) {
  13503. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13504. this._gl.bindBuffer(target, buffer);
  13505. this._currentBoundBuffer[target] = buffer;
  13506. }
  13507. };
  13508. /**
  13509. * update the bound buffer with the given data
  13510. * @param data defines the data to update
  13511. */
  13512. Engine.prototype.updateArrayBuffer = function (data) {
  13513. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13514. };
  13515. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13516. var pointer = this._currentBufferPointers[indx];
  13517. var changed = false;
  13518. if (!pointer.active) {
  13519. changed = true;
  13520. pointer.active = true;
  13521. pointer.index = indx;
  13522. pointer.size = size;
  13523. pointer.type = type;
  13524. pointer.normalized = normalized;
  13525. pointer.stride = stride;
  13526. pointer.offset = offset;
  13527. pointer.buffer = buffer;
  13528. }
  13529. else {
  13530. if (pointer.buffer !== buffer) {
  13531. pointer.buffer = buffer;
  13532. changed = true;
  13533. }
  13534. if (pointer.size !== size) {
  13535. pointer.size = size;
  13536. changed = true;
  13537. }
  13538. if (pointer.type !== type) {
  13539. pointer.type = type;
  13540. changed = true;
  13541. }
  13542. if (pointer.normalized !== normalized) {
  13543. pointer.normalized = normalized;
  13544. changed = true;
  13545. }
  13546. if (pointer.stride !== stride) {
  13547. pointer.stride = stride;
  13548. changed = true;
  13549. }
  13550. if (pointer.offset !== offset) {
  13551. pointer.offset = offset;
  13552. changed = true;
  13553. }
  13554. }
  13555. if (changed || this._vaoRecordInProgress) {
  13556. this.bindArrayBuffer(buffer);
  13557. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13558. }
  13559. };
  13560. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13561. if (indexBuffer == null) {
  13562. return;
  13563. }
  13564. if (this._cachedIndexBuffer !== indexBuffer) {
  13565. this._cachedIndexBuffer = indexBuffer;
  13566. this.bindIndexBuffer(indexBuffer);
  13567. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13568. }
  13569. };
  13570. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13571. var attributes = effect.getAttributesNames();
  13572. if (!this._vaoRecordInProgress) {
  13573. this._unbindVertexArrayObject();
  13574. }
  13575. this.unbindAllAttributes();
  13576. for (var index = 0; index < attributes.length; index++) {
  13577. var order = effect.getAttributeLocation(index);
  13578. if (order >= 0) {
  13579. var vertexBuffer = vertexBuffers[attributes[index]];
  13580. if (!vertexBuffer) {
  13581. continue;
  13582. }
  13583. this._gl.enableVertexAttribArray(order);
  13584. if (!this._vaoRecordInProgress) {
  13585. this._vertexAttribArraysEnabled[order] = true;
  13586. }
  13587. var buffer = vertexBuffer.getBuffer();
  13588. if (buffer) {
  13589. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13590. if (vertexBuffer.getIsInstanced()) {
  13591. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13592. if (!this._vaoRecordInProgress) {
  13593. this._currentInstanceLocations.push(order);
  13594. this._currentInstanceBuffers.push(buffer);
  13595. }
  13596. }
  13597. }
  13598. }
  13599. }
  13600. };
  13601. /**
  13602. * Records a vertex array object
  13603. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13604. * @param vertexBuffers defines the list of vertex buffers to store
  13605. * @param indexBuffer defines the index buffer to store
  13606. * @param effect defines the effect to store
  13607. * @returns the new vertex array object
  13608. */
  13609. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13610. var vao = this._gl.createVertexArray();
  13611. this._vaoRecordInProgress = true;
  13612. this._gl.bindVertexArray(vao);
  13613. this._mustWipeVertexAttributes = true;
  13614. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13615. this.bindIndexBuffer(indexBuffer);
  13616. this._vaoRecordInProgress = false;
  13617. this._gl.bindVertexArray(null);
  13618. return vao;
  13619. };
  13620. /**
  13621. * Bind a specific vertex array object
  13622. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13623. * @param vertexArrayObject defines the vertex array object to bind
  13624. * @param indexBuffer defines the index buffer to bind
  13625. */
  13626. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13627. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13628. this._cachedVertexArrayObject = vertexArrayObject;
  13629. this._gl.bindVertexArray(vertexArrayObject);
  13630. this._cachedVertexBuffers = null;
  13631. this._cachedIndexBuffer = null;
  13632. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13633. this._mustWipeVertexAttributes = true;
  13634. }
  13635. };
  13636. /**
  13637. * Bind webGl buffers directly to the webGL context
  13638. * @param vertexBuffer defines the vertex buffer to bind
  13639. * @param indexBuffer defines the index buffer to bind
  13640. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13641. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13642. * @param effect defines the effect associated with the vertex buffer
  13643. */
  13644. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13645. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13646. this._cachedVertexBuffers = vertexBuffer;
  13647. this._cachedEffectForVertexBuffers = effect;
  13648. var attributesCount = effect.getAttributesCount();
  13649. this._unbindVertexArrayObject();
  13650. this.unbindAllAttributes();
  13651. var offset = 0;
  13652. for (var index = 0; index < attributesCount; index++) {
  13653. if (index < vertexDeclaration.length) {
  13654. var order = effect.getAttributeLocation(index);
  13655. if (order >= 0) {
  13656. this._gl.enableVertexAttribArray(order);
  13657. this._vertexAttribArraysEnabled[order] = true;
  13658. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13659. }
  13660. offset += vertexDeclaration[index] * 4;
  13661. }
  13662. }
  13663. }
  13664. this._bindIndexBufferWithCache(indexBuffer);
  13665. };
  13666. Engine.prototype._unbindVertexArrayObject = function () {
  13667. if (!this._cachedVertexArrayObject) {
  13668. return;
  13669. }
  13670. this._cachedVertexArrayObject = null;
  13671. this._gl.bindVertexArray(null);
  13672. };
  13673. /**
  13674. * Bind a list of vertex buffers to the webGL context
  13675. * @param vertexBuffers defines the list of vertex buffers to bind
  13676. * @param indexBuffer defines the index buffer to bind
  13677. * @param effect defines the effect associated with the vertex buffers
  13678. */
  13679. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13680. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13681. this._cachedVertexBuffers = vertexBuffers;
  13682. this._cachedEffectForVertexBuffers = effect;
  13683. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13684. }
  13685. this._bindIndexBufferWithCache(indexBuffer);
  13686. };
  13687. /**
  13688. * Unbind all instance attributes
  13689. */
  13690. Engine.prototype.unbindInstanceAttributes = function () {
  13691. var boundBuffer;
  13692. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13693. var instancesBuffer = this._currentInstanceBuffers[i];
  13694. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13695. boundBuffer = instancesBuffer;
  13696. this.bindArrayBuffer(instancesBuffer);
  13697. }
  13698. var offsetLocation = this._currentInstanceLocations[i];
  13699. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13700. }
  13701. this._currentInstanceBuffers.length = 0;
  13702. this._currentInstanceLocations.length = 0;
  13703. };
  13704. /**
  13705. * Release and free the memory of a vertex array object
  13706. * @param vao defines the vertex array object to delete
  13707. */
  13708. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13709. this._gl.deleteVertexArray(vao);
  13710. };
  13711. /** @hidden */
  13712. Engine.prototype._releaseBuffer = function (buffer) {
  13713. buffer.references--;
  13714. if (buffer.references === 0) {
  13715. this._gl.deleteBuffer(buffer);
  13716. return true;
  13717. }
  13718. return false;
  13719. };
  13720. /**
  13721. * Creates a webGL buffer to use with instanciation
  13722. * @param capacity defines the size of the buffer
  13723. * @returns the webGL buffer
  13724. */
  13725. Engine.prototype.createInstancesBuffer = function (capacity) {
  13726. var buffer = this._gl.createBuffer();
  13727. if (!buffer) {
  13728. throw new Error("Unable to create instance buffer");
  13729. }
  13730. buffer.capacity = capacity;
  13731. this.bindArrayBuffer(buffer);
  13732. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13733. return buffer;
  13734. };
  13735. /**
  13736. * Delete a webGL buffer used with instanciation
  13737. * @param buffer defines the webGL buffer to delete
  13738. */
  13739. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13740. this._gl.deleteBuffer(buffer);
  13741. };
  13742. /**
  13743. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13744. * @param instancesBuffer defines the webGL buffer to update and bind
  13745. * @param data defines the data to store in the buffer
  13746. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13747. */
  13748. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13749. this.bindArrayBuffer(instancesBuffer);
  13750. if (data) {
  13751. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13752. }
  13753. if (offsetLocations[0].index !== undefined) {
  13754. var stride = 0;
  13755. for (var i = 0; i < offsetLocations.length; i++) {
  13756. var ai = offsetLocations[i];
  13757. stride += ai.attributeSize * 4;
  13758. }
  13759. for (var i = 0; i < offsetLocations.length; i++) {
  13760. var ai = offsetLocations[i];
  13761. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13762. this._gl.enableVertexAttribArray(ai.index);
  13763. this._vertexAttribArraysEnabled[ai.index] = true;
  13764. }
  13765. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13766. this._gl.vertexAttribDivisor(ai.index, 1);
  13767. this._currentInstanceLocations.push(ai.index);
  13768. this._currentInstanceBuffers.push(instancesBuffer);
  13769. }
  13770. }
  13771. else {
  13772. for (var index = 0; index < 4; index++) {
  13773. var offsetLocation = offsetLocations[index];
  13774. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13775. this._gl.enableVertexAttribArray(offsetLocation);
  13776. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13777. }
  13778. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13779. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13780. this._currentInstanceLocations.push(offsetLocation);
  13781. this._currentInstanceBuffers.push(instancesBuffer);
  13782. }
  13783. }
  13784. };
  13785. /**
  13786. * Apply all cached states (depth, culling, stencil and alpha)
  13787. */
  13788. Engine.prototype.applyStates = function () {
  13789. this._depthCullingState.apply(this._gl);
  13790. this._stencilState.apply(this._gl);
  13791. this._alphaState.apply(this._gl);
  13792. };
  13793. /**
  13794. * Send a draw order
  13795. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13796. * @param indexStart defines the starting index
  13797. * @param indexCount defines the number of index to draw
  13798. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13799. */
  13800. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13801. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13802. };
  13803. /**
  13804. * Draw a list of points
  13805. * @param verticesStart defines the index of first vertex to draw
  13806. * @param verticesCount defines the count of vertices to draw
  13807. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13808. */
  13809. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13810. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13811. };
  13812. /**
  13813. * Draw a list of unindexed primitives
  13814. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13815. * @param verticesStart defines the index of first vertex to draw
  13816. * @param verticesCount defines the count of vertices to draw
  13817. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13818. */
  13819. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13820. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13821. };
  13822. /**
  13823. * Draw a list of indexed primitives
  13824. * @param fillMode defines the primitive to use
  13825. * @param indexStart defines the starting index
  13826. * @param indexCount defines the number of index to draw
  13827. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13828. */
  13829. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13830. // Apply states
  13831. this.applyStates();
  13832. this._drawCalls.addCount(1, false);
  13833. // Render
  13834. var drawMode = this._drawMode(fillMode);
  13835. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13836. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13837. if (instancesCount) {
  13838. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13839. }
  13840. else {
  13841. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13842. }
  13843. };
  13844. /**
  13845. * Draw a list of unindexed primitives
  13846. * @param fillMode defines the primitive to use
  13847. * @param verticesStart defines the index of first vertex to draw
  13848. * @param verticesCount defines the count of vertices to draw
  13849. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13850. */
  13851. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13852. // Apply states
  13853. this.applyStates();
  13854. this._drawCalls.addCount(1, false);
  13855. var drawMode = this._drawMode(fillMode);
  13856. if (instancesCount) {
  13857. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13858. }
  13859. else {
  13860. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13861. }
  13862. };
  13863. Engine.prototype._drawMode = function (fillMode) {
  13864. switch (fillMode) {
  13865. // Triangle views
  13866. case BABYLON.Material.TriangleFillMode:
  13867. return this._gl.TRIANGLES;
  13868. case BABYLON.Material.PointFillMode:
  13869. return this._gl.POINTS;
  13870. case BABYLON.Material.WireFrameFillMode:
  13871. return this._gl.LINES;
  13872. // Draw modes
  13873. case BABYLON.Material.PointListDrawMode:
  13874. return this._gl.POINTS;
  13875. case BABYLON.Material.LineListDrawMode:
  13876. return this._gl.LINES;
  13877. case BABYLON.Material.LineLoopDrawMode:
  13878. return this._gl.LINE_LOOP;
  13879. case BABYLON.Material.LineStripDrawMode:
  13880. return this._gl.LINE_STRIP;
  13881. case BABYLON.Material.TriangleStripDrawMode:
  13882. return this._gl.TRIANGLE_STRIP;
  13883. case BABYLON.Material.TriangleFanDrawMode:
  13884. return this._gl.TRIANGLE_FAN;
  13885. default:
  13886. return this._gl.TRIANGLES;
  13887. }
  13888. };
  13889. // Shaders
  13890. /** @hidden */
  13891. Engine.prototype._releaseEffect = function (effect) {
  13892. if (this._compiledEffects[effect._key]) {
  13893. delete this._compiledEffects[effect._key];
  13894. this._deleteProgram(effect.getProgram());
  13895. }
  13896. };
  13897. /** @hidden */
  13898. Engine.prototype._deleteProgram = function (program) {
  13899. if (program) {
  13900. program.__SPECTOR_rebuildProgram = null;
  13901. if (program.transformFeedback) {
  13902. this.deleteTransformFeedback(program.transformFeedback);
  13903. program.transformFeedback = null;
  13904. }
  13905. this._gl.deleteProgram(program);
  13906. }
  13907. };
  13908. /**
  13909. * Create a new effect (used to store vertex/fragment shaders)
  13910. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13911. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13912. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13913. * @param samplers defines an array of string used to represent textures
  13914. * @param defines defines the string containing the defines to use to compile the shaders
  13915. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13916. * @param onCompiled defines a function to call when the effect creation is successful
  13917. * @param onError defines a function to call when the effect creation has failed
  13918. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13919. * @returns the new Effect
  13920. */
  13921. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13922. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13923. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13924. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13925. if (this._compiledEffects[name]) {
  13926. var compiledEffect = this._compiledEffects[name];
  13927. if (onCompiled && compiledEffect.isReady()) {
  13928. onCompiled(compiledEffect);
  13929. }
  13930. return compiledEffect;
  13931. }
  13932. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13933. effect._key = name;
  13934. this._compiledEffects[name] = effect;
  13935. return effect;
  13936. };
  13937. /**
  13938. * Create an effect to use with particle systems
  13939. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13940. * @param uniformsNames defines a list of attribute names
  13941. * @param samplers defines an array of string used to represent textures
  13942. * @param defines defines the string containing the defines to use to compile the shaders
  13943. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13944. * @param onCompiled defines a function to call when the effect creation is successful
  13945. * @param onError defines a function to call when the effect creation has failed
  13946. * @returns the new Effect
  13947. */
  13948. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13949. if (uniformsNames === void 0) { uniformsNames = []; }
  13950. if (samplers === void 0) { samplers = []; }
  13951. if (defines === void 0) { defines = ""; }
  13952. return this.createEffect({
  13953. vertex: "particles",
  13954. fragmentElement: fragmentName
  13955. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13956. };
  13957. /**
  13958. * Directly creates a webGL program
  13959. * @param vertexCode defines the vertex shader code to use
  13960. * @param fragmentCode defines the fragment shader code to use
  13961. * @param context defines the webGL context to use (if not set, the current one will be used)
  13962. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13963. * @returns the new webGL program
  13964. */
  13965. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13966. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13967. context = context || this._gl;
  13968. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13969. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13970. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13971. };
  13972. /**
  13973. * Creates a webGL program
  13974. * @param vertexCode defines the vertex shader code to use
  13975. * @param fragmentCode defines the fragment shader code to use
  13976. * @param defines defines the string containing the defines to use to compile the shaders
  13977. * @param context defines the webGL context to use (if not set, the current one will be used)
  13978. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13979. * @returns the new webGL program
  13980. */
  13981. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13982. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13983. context = context || this._gl;
  13984. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13985. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13986. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13987. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13988. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13989. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13990. return program;
  13991. };
  13992. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13993. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13994. var shaderProgram = context.createProgram();
  13995. if (!shaderProgram) {
  13996. throw new Error("Unable to create program");
  13997. }
  13998. context.attachShader(shaderProgram, vertexShader);
  13999. context.attachShader(shaderProgram, fragmentShader);
  14000. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14001. var transformFeedback = this.createTransformFeedback();
  14002. this.bindTransformFeedback(transformFeedback);
  14003. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14004. shaderProgram.transformFeedback = transformFeedback;
  14005. }
  14006. context.linkProgram(shaderProgram);
  14007. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14008. this.bindTransformFeedback(null);
  14009. }
  14010. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14011. if (!linked) {
  14012. context.validateProgram(shaderProgram);
  14013. var error = context.getProgramInfoLog(shaderProgram);
  14014. if (error) {
  14015. throw new Error(error);
  14016. }
  14017. }
  14018. context.deleteShader(vertexShader);
  14019. context.deleteShader(fragmentShader);
  14020. return shaderProgram;
  14021. };
  14022. /**
  14023. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14024. * @param shaderProgram defines the webGL program to use
  14025. * @param uniformsNames defines the list of uniform names
  14026. * @returns an array of webGL uniform locations
  14027. */
  14028. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14029. var results = new Array();
  14030. for (var index = 0; index < uniformsNames.length; index++) {
  14031. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14032. }
  14033. return results;
  14034. };
  14035. /**
  14036. * Gets the lsit of active attributes for a given webGL program
  14037. * @param shaderProgram defines the webGL program to use
  14038. * @param attributesNames defines the list of attribute names to get
  14039. * @returns an array of indices indicating the offset of each attribute
  14040. */
  14041. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14042. var results = [];
  14043. for (var index = 0; index < attributesNames.length; index++) {
  14044. try {
  14045. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14046. }
  14047. catch (e) {
  14048. results.push(-1);
  14049. }
  14050. }
  14051. return results;
  14052. };
  14053. /**
  14054. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14055. * @param effect defines the effect to activate
  14056. */
  14057. Engine.prototype.enableEffect = function (effect) {
  14058. if (!effect) {
  14059. return;
  14060. }
  14061. // Use program
  14062. this.bindSamplers(effect);
  14063. this._currentEffect = effect;
  14064. if (effect.onBind) {
  14065. effect.onBind(effect);
  14066. }
  14067. effect.onBindObservable.notifyObservers(effect);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of int32
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of int32 to store
  14073. */
  14074. Engine.prototype.setIntArray = function (uniform, array) {
  14075. if (!uniform)
  14076. return;
  14077. this._gl.uniform1iv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of int32 (stored as vec2)
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param array defines the array of int32 to store
  14083. */
  14084. Engine.prototype.setIntArray2 = function (uniform, array) {
  14085. if (!uniform || array.length % 2 !== 0)
  14086. return;
  14087. this._gl.uniform2iv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of int32 (stored as vec3)
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of int32 to store
  14093. */
  14094. Engine.prototype.setIntArray3 = function (uniform, array) {
  14095. if (!uniform || array.length % 3 !== 0)
  14096. return;
  14097. this._gl.uniform3iv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of int32 (stored as vec4)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param array defines the array of int32 to store
  14103. */
  14104. Engine.prototype.setIntArray4 = function (uniform, array) {
  14105. if (!uniform || array.length % 4 !== 0)
  14106. return;
  14107. this._gl.uniform4iv(uniform, array);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to an array of float32
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param array defines the array of float32 to store
  14113. */
  14114. Engine.prototype.setFloatArray = function (uniform, array) {
  14115. if (!uniform)
  14116. return;
  14117. this._gl.uniform1fv(uniform, array);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to an array of float32 (stored as vec2)
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param array defines the array of float32 to store
  14123. */
  14124. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14125. if (!uniform || array.length % 2 !== 0)
  14126. return;
  14127. this._gl.uniform2fv(uniform, array);
  14128. };
  14129. /**
  14130. * Set the value of an uniform to an array of float32 (stored as vec3)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param array defines the array of float32 to store
  14133. */
  14134. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14135. if (!uniform || array.length % 3 !== 0)
  14136. return;
  14137. this._gl.uniform3fv(uniform, array);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to an array of float32 (stored as vec4)
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param array defines the array of float32 to store
  14143. */
  14144. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14145. if (!uniform || array.length % 4 !== 0)
  14146. return;
  14147. this._gl.uniform4fv(uniform, array);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to an array of number
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param array defines the array of number to store
  14153. */
  14154. Engine.prototype.setArray = function (uniform, array) {
  14155. if (!uniform)
  14156. return;
  14157. this._gl.uniform1fv(uniform, array);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to an array of number (stored as vec2)
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param array defines the array of number to store
  14163. */
  14164. Engine.prototype.setArray2 = function (uniform, array) {
  14165. if (!uniform || array.length % 2 !== 0)
  14166. return;
  14167. this._gl.uniform2fv(uniform, array);
  14168. };
  14169. /**
  14170. * Set the value of an uniform to an array of number (stored as vec3)
  14171. * @param uniform defines the webGL uniform location where to store the value
  14172. * @param array defines the array of number to store
  14173. */
  14174. Engine.prototype.setArray3 = function (uniform, array) {
  14175. if (!uniform || array.length % 3 !== 0)
  14176. return;
  14177. this._gl.uniform3fv(uniform, array);
  14178. };
  14179. /**
  14180. * Set the value of an uniform to an array of number (stored as vec4)
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param array defines the array of number to store
  14183. */
  14184. Engine.prototype.setArray4 = function (uniform, array) {
  14185. if (!uniform || array.length % 4 !== 0)
  14186. return;
  14187. this._gl.uniform4fv(uniform, array);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to an array of float32 (stored as matrices)
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param matrices defines the array of float32 to store
  14193. */
  14194. Engine.prototype.setMatrices = function (uniform, matrices) {
  14195. if (!uniform)
  14196. return;
  14197. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14198. };
  14199. /**
  14200. * Set the value of an uniform to a matrix
  14201. * @param uniform defines the webGL uniform location where to store the value
  14202. * @param matrix defines the matrix to store
  14203. */
  14204. Engine.prototype.setMatrix = function (uniform, matrix) {
  14205. if (!uniform)
  14206. return;
  14207. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14208. };
  14209. /**
  14210. * Set the value of an uniform to a matrix (3x3)
  14211. * @param uniform defines the webGL uniform location where to store the value
  14212. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14213. */
  14214. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14215. if (!uniform)
  14216. return;
  14217. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14218. };
  14219. /**
  14220. * Set the value of an uniform to a matrix (2x2)
  14221. * @param uniform defines the webGL uniform location where to store the value
  14222. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14223. */
  14224. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14225. if (!uniform)
  14226. return;
  14227. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14228. };
  14229. /**
  14230. * Set the value of an uniform to a number (int)
  14231. * @param uniform defines the webGL uniform location where to store the value
  14232. * @param value defines the int number to store
  14233. */
  14234. Engine.prototype.setInt = function (uniform, value) {
  14235. if (!uniform)
  14236. return;
  14237. this._gl.uniform1i(uniform, value);
  14238. };
  14239. /**
  14240. * Set the value of an uniform to a number (float)
  14241. * @param uniform defines the webGL uniform location where to store the value
  14242. * @param value defines the float number to store
  14243. */
  14244. Engine.prototype.setFloat = function (uniform, value) {
  14245. if (!uniform)
  14246. return;
  14247. this._gl.uniform1f(uniform, value);
  14248. };
  14249. /**
  14250. * Set the value of an uniform to a vec2
  14251. * @param uniform defines the webGL uniform location where to store the value
  14252. * @param x defines the 1st component of the value
  14253. * @param y defines the 2nd component of the value
  14254. */
  14255. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14256. if (!uniform)
  14257. return;
  14258. this._gl.uniform2f(uniform, x, y);
  14259. };
  14260. /**
  14261. * Set the value of an uniform to a vec3
  14262. * @param uniform defines the webGL uniform location where to store the value
  14263. * @param x defines the 1st component of the value
  14264. * @param y defines the 2nd component of the value
  14265. * @param z defines the 3rd component of the value
  14266. */
  14267. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14268. if (!uniform)
  14269. return;
  14270. this._gl.uniform3f(uniform, x, y, z);
  14271. };
  14272. /**
  14273. * Set the value of an uniform to a boolean
  14274. * @param uniform defines the webGL uniform location where to store the value
  14275. * @param bool defines the boolean to store
  14276. */
  14277. Engine.prototype.setBool = function (uniform, bool) {
  14278. if (!uniform)
  14279. return;
  14280. this._gl.uniform1i(uniform, bool);
  14281. };
  14282. /**
  14283. * Set the value of an uniform to a vec4
  14284. * @param uniform defines the webGL uniform location where to store the value
  14285. * @param x defines the 1st component of the value
  14286. * @param y defines the 2nd component of the value
  14287. * @param z defines the 3rd component of the value
  14288. * @param w defines the 4th component of the value
  14289. */
  14290. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14291. if (!uniform)
  14292. return;
  14293. this._gl.uniform4f(uniform, x, y, z, w);
  14294. };
  14295. /**
  14296. * Set the value of an uniform to a Color3
  14297. * @param uniform defines the webGL uniform location where to store the value
  14298. * @param color3 defines the color to store
  14299. */
  14300. Engine.prototype.setColor3 = function (uniform, color3) {
  14301. if (!uniform)
  14302. return;
  14303. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14304. };
  14305. /**
  14306. * Set the value of an uniform to a Color3 and an alpha value
  14307. * @param uniform defines the webGL uniform location where to store the value
  14308. * @param color3 defines the color to store
  14309. * @param alpha defines the alpha component to store
  14310. */
  14311. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14312. if (!uniform)
  14313. return;
  14314. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14315. };
  14316. /**
  14317. * Sets a Color4 on a uniform variable
  14318. * @param uniform defines the uniform location
  14319. * @param color4 defines the value to be set
  14320. */
  14321. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14322. if (!uniform)
  14323. return;
  14324. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14325. };
  14326. // States
  14327. /**
  14328. * Set various states to the webGL context
  14329. * @param culling defines backface culling state
  14330. * @param zOffset defines the value to apply to zOffset (0 by default)
  14331. * @param force defines if states must be applied even if cache is up to date
  14332. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14333. */
  14334. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14335. if (zOffset === void 0) { zOffset = 0; }
  14336. if (reverseSide === void 0) { reverseSide = false; }
  14337. // Culling
  14338. if (this._depthCullingState.cull !== culling || force) {
  14339. this._depthCullingState.cull = culling;
  14340. }
  14341. // Cull face
  14342. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14343. if (this._depthCullingState.cullFace !== cullFace || force) {
  14344. this._depthCullingState.cullFace = cullFace;
  14345. }
  14346. // Z offset
  14347. this.setZOffset(zOffset);
  14348. // Front face
  14349. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14350. if (this._depthCullingState.frontFace !== frontFace || force) {
  14351. this._depthCullingState.frontFace = frontFace;
  14352. }
  14353. };
  14354. /**
  14355. * Set the z offset to apply to current rendering
  14356. * @param value defines the offset to apply
  14357. */
  14358. Engine.prototype.setZOffset = function (value) {
  14359. this._depthCullingState.zOffset = value;
  14360. };
  14361. /**
  14362. * Gets the current value of the zOffset
  14363. * @returns the current zOffset state
  14364. */
  14365. Engine.prototype.getZOffset = function () {
  14366. return this._depthCullingState.zOffset;
  14367. };
  14368. /**
  14369. * Enable or disable depth buffering
  14370. * @param enable defines the state to set
  14371. */
  14372. Engine.prototype.setDepthBuffer = function (enable) {
  14373. this._depthCullingState.depthTest = enable;
  14374. };
  14375. /**
  14376. * Gets a boolean indicating if depth writing is enabled
  14377. * @returns the current depth writing state
  14378. */
  14379. Engine.prototype.getDepthWrite = function () {
  14380. return this._depthCullingState.depthMask;
  14381. };
  14382. /**
  14383. * Enable or disable depth writing
  14384. * @param enable defines the state to set
  14385. */
  14386. Engine.prototype.setDepthWrite = function (enable) {
  14387. this._depthCullingState.depthMask = enable;
  14388. };
  14389. /**
  14390. * Enable or disable color writing
  14391. * @param enable defines the state to set
  14392. */
  14393. Engine.prototype.setColorWrite = function (enable) {
  14394. this._gl.colorMask(enable, enable, enable, enable);
  14395. this._colorWrite = enable;
  14396. };
  14397. /**
  14398. * Gets a boolean indicating if color writing is enabled
  14399. * @returns the current color writing state
  14400. */
  14401. Engine.prototype.getColorWrite = function () {
  14402. return this._colorWrite;
  14403. };
  14404. /**
  14405. * Sets alpha constants used by some alpha blending modes
  14406. * @param r defines the red component
  14407. * @param g defines the green component
  14408. * @param b defines the blue component
  14409. * @param a defines the alpha component
  14410. */
  14411. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14412. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14413. };
  14414. /**
  14415. * Sets the current alpha mode
  14416. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14417. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14418. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14419. */
  14420. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14421. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14422. if (this._alphaMode === mode) {
  14423. return;
  14424. }
  14425. switch (mode) {
  14426. case Engine.ALPHA_DISABLE:
  14427. this._alphaState.alphaBlend = false;
  14428. break;
  14429. case Engine.ALPHA_PREMULTIPLIED:
  14430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14431. this._alphaState.alphaBlend = true;
  14432. break;
  14433. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14435. this._alphaState.alphaBlend = true;
  14436. break;
  14437. case Engine.ALPHA_COMBINE:
  14438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14439. this._alphaState.alphaBlend = true;
  14440. break;
  14441. case Engine.ALPHA_ONEONE:
  14442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14443. this._alphaState.alphaBlend = true;
  14444. break;
  14445. case Engine.ALPHA_ADD:
  14446. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14447. this._alphaState.alphaBlend = true;
  14448. break;
  14449. case Engine.ALPHA_SUBTRACT:
  14450. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14451. this._alphaState.alphaBlend = true;
  14452. break;
  14453. case Engine.ALPHA_MULTIPLY:
  14454. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14455. this._alphaState.alphaBlend = true;
  14456. break;
  14457. case Engine.ALPHA_MAXIMIZED:
  14458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14459. this._alphaState.alphaBlend = true;
  14460. break;
  14461. case Engine.ALPHA_INTERPOLATE:
  14462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14463. this._alphaState.alphaBlend = true;
  14464. break;
  14465. case Engine.ALPHA_SCREENMODE:
  14466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14467. this._alphaState.alphaBlend = true;
  14468. break;
  14469. }
  14470. if (!noDepthWriteChange) {
  14471. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14472. }
  14473. this._alphaMode = mode;
  14474. };
  14475. /**
  14476. * Gets the current alpha mode
  14477. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14478. * @returns the current alpha mode
  14479. */
  14480. Engine.prototype.getAlphaMode = function () {
  14481. return this._alphaMode;
  14482. };
  14483. // Textures
  14484. /**
  14485. * Force the entire cache to be cleared
  14486. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14487. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14488. */
  14489. Engine.prototype.wipeCaches = function (bruteForce) {
  14490. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14491. return;
  14492. }
  14493. this._currentEffect = null;
  14494. if (bruteForce) {
  14495. this.resetTextureCache();
  14496. this._currentProgram = null;
  14497. this._stencilState.reset();
  14498. this._depthCullingState.reset();
  14499. this.setDepthFunctionToLessOrEqual();
  14500. this._alphaState.reset();
  14501. }
  14502. this._resetVertexBufferBinding();
  14503. this._cachedIndexBuffer = null;
  14504. this._cachedEffectForVertexBuffers = null;
  14505. this._unbindVertexArrayObject();
  14506. this.bindIndexBuffer(null);
  14507. };
  14508. /**
  14509. * Set the compressed texture format to use, based on the formats you have, and the formats
  14510. * supported by the hardware / browser.
  14511. *
  14512. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14513. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14514. * to API arguments needed to compressed textures. This puts the burden on the container
  14515. * generator to house the arcane code for determining these for current & future formats.
  14516. *
  14517. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14518. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14519. *
  14520. * Note: The result of this call is not taken into account when a texture is base64.
  14521. *
  14522. * @param formatsAvailable defines the list of those format families you have created
  14523. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14524. *
  14525. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14526. * @returns The extension selected.
  14527. */
  14528. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14529. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14530. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14531. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14532. return this._textureFormatInUse = this._texturesSupported[i];
  14533. }
  14534. }
  14535. }
  14536. // actively set format to nothing, to allow this to be called more than once
  14537. // and possibly fail the 2nd time
  14538. this._textureFormatInUse = null;
  14539. return null;
  14540. };
  14541. /** @hidden */
  14542. Engine.prototype._createTexture = function () {
  14543. var texture = this._gl.createTexture();
  14544. if (!texture) {
  14545. throw new Error("Unable to create texture");
  14546. }
  14547. return texture;
  14548. };
  14549. /**
  14550. * Usually called from BABYLON.Texture.ts.
  14551. * Passed information to create a WebGLTexture
  14552. * @param urlArg defines a value which contains one of the following:
  14553. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14554. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14555. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14556. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14557. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14558. * @param scene needed for loading to the correct scene
  14559. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14560. * @param onLoad optional callback to be called upon successful completion
  14561. * @param onError optional callback to be called upon failure
  14562. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14563. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14564. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14565. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14566. */
  14567. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14568. var _this = this;
  14569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14570. if (onLoad === void 0) { onLoad = null; }
  14571. if (onError === void 0) { onError = null; }
  14572. if (buffer === void 0) { buffer = null; }
  14573. if (fallback === void 0) { fallback = null; }
  14574. if (format === void 0) { format = null; }
  14575. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14576. var fromData = url.substr(0, 5) === "data:";
  14577. var fromBlob = url.substr(0, 5) === "blob:";
  14578. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14579. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14580. // establish the file extension, if possible
  14581. var lastDot = url.lastIndexOf('.');
  14582. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14583. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14584. var isTGA = (extension.indexOf(".tga") === 0);
  14585. // determine if a ktx file should be substituted
  14586. var isKTX = false;
  14587. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14588. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14589. isKTX = true;
  14590. }
  14591. if (scene) {
  14592. scene._addPendingData(texture);
  14593. }
  14594. texture.url = url;
  14595. texture.generateMipMaps = !noMipmap;
  14596. texture.samplingMode = samplingMode;
  14597. texture.invertY = invertY;
  14598. if (!this._doNotHandleContextLost) {
  14599. // Keep a link to the buffer only if we plan to handle context lost
  14600. texture._buffer = buffer;
  14601. }
  14602. var onLoadObserver = null;
  14603. if (onLoad && !fallback) {
  14604. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14605. }
  14606. if (!fallback)
  14607. this._internalTexturesCache.push(texture);
  14608. var onerror = function (message, exception) {
  14609. if (scene) {
  14610. scene._removePendingData(texture);
  14611. }
  14612. if (onLoadObserver) {
  14613. texture.onLoadedObservable.remove(onLoadObserver);
  14614. }
  14615. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14616. if (isKTX) {
  14617. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14618. }
  14619. else if (BABYLON.Tools.UseFallbackTexture) {
  14620. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14621. }
  14622. if (onError) {
  14623. onError(message || "Unknown error", exception);
  14624. }
  14625. };
  14626. var callback = null;
  14627. // processing for non-image formats
  14628. if (isKTX || isTGA || isDDS) {
  14629. if (isKTX) {
  14630. callback = function (data) {
  14631. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14632. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14633. ktx.uploadLevels(_this._gl, !noMipmap);
  14634. return false;
  14635. }, samplingMode);
  14636. };
  14637. }
  14638. else if (isTGA) {
  14639. callback = function (arrayBuffer) {
  14640. var data = new Uint8Array(arrayBuffer);
  14641. var header = BABYLON.TGATools.GetTGAHeader(data);
  14642. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14643. BABYLON.TGATools.UploadContent(_this._gl, data);
  14644. return false;
  14645. }, samplingMode);
  14646. };
  14647. }
  14648. else if (isDDS) {
  14649. callback = function (data) {
  14650. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14651. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14652. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14653. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14654. return false;
  14655. }, samplingMode);
  14656. };
  14657. }
  14658. if (!buffer) {
  14659. this._loadFile(url, function (data) {
  14660. if (callback) {
  14661. callback(data);
  14662. }
  14663. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14664. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14665. });
  14666. }
  14667. else {
  14668. if (callback) {
  14669. callback(buffer);
  14670. }
  14671. }
  14672. // image format processing
  14673. }
  14674. else {
  14675. var onload = function (img) {
  14676. if (fromBlob && !_this._doNotHandleContextLost) {
  14677. // We need to store the image if we need to rebuild the texture
  14678. // in case of a webgl context lost
  14679. texture._buffer = img;
  14680. }
  14681. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14682. var gl = _this._gl;
  14683. var isPot = (img.width === potWidth && img.height === potHeight);
  14684. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14685. if (isPot) {
  14686. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14687. return false;
  14688. }
  14689. // Using shaders to rescale because canvas.drawImage is lossy
  14690. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14691. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14692. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14695. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14696. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14697. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14698. _this._releaseTexture(source);
  14699. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14700. continuationCallback();
  14701. });
  14702. return true;
  14703. }, samplingMode);
  14704. };
  14705. if (!fromData || isBase64) {
  14706. if (buffer instanceof HTMLImageElement) {
  14707. onload(buffer);
  14708. }
  14709. else {
  14710. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14711. }
  14712. }
  14713. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14714. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14715. }
  14716. else {
  14717. onload(buffer);
  14718. }
  14719. }
  14720. return texture;
  14721. };
  14722. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14723. var _this = this;
  14724. var rtt = this.createRenderTargetTexture({
  14725. width: destination.width,
  14726. height: destination.height,
  14727. }, {
  14728. generateMipMaps: false,
  14729. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14730. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14731. generateDepthBuffer: false,
  14732. generateStencilBuffer: false
  14733. });
  14734. if (!this._rescalePostProcess) {
  14735. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14736. }
  14737. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14738. _this._rescalePostProcess.onApply = function (effect) {
  14739. effect._bindTexture("textureSampler", source);
  14740. };
  14741. var hostingScene = scene;
  14742. if (!hostingScene) {
  14743. hostingScene = _this.scenes[_this.scenes.length - 1];
  14744. }
  14745. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14746. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14747. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14748. _this.unBindFramebuffer(rtt);
  14749. _this._releaseTexture(rtt);
  14750. if (onComplete) {
  14751. onComplete();
  14752. }
  14753. });
  14754. };
  14755. /**
  14756. * Update a raw texture
  14757. * @param texture defines the texture to update
  14758. * @param data defines the data to store in the texture
  14759. * @param format defines the format of the data
  14760. * @param invertY defines if data must be stored with Y axis inverted
  14761. * @param compression defines the compression used (null by default)
  14762. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14763. */
  14764. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14765. if (compression === void 0) { compression = null; }
  14766. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14767. if (!texture) {
  14768. return;
  14769. }
  14770. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14771. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14772. // babylon's internalFormat but gl's texImage2D format
  14773. var internalFormat = this._getInternalFormat(format);
  14774. var textureType = this._getWebGLTextureType(type);
  14775. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14776. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14777. if (!this._doNotHandleContextLost) {
  14778. texture._bufferView = data;
  14779. texture.format = format;
  14780. texture.type = type;
  14781. texture.invertY = invertY;
  14782. texture._compression = compression;
  14783. }
  14784. if (texture.width % 4 !== 0) {
  14785. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14786. }
  14787. if (compression && data) {
  14788. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14789. }
  14790. else {
  14791. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14792. }
  14793. if (texture.generateMipMaps) {
  14794. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14795. }
  14796. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14797. // this.resetTextureCache();
  14798. texture.isReady = true;
  14799. };
  14800. /**
  14801. * Creates a raw texture
  14802. * @param data defines the data to store in the texture
  14803. * @param width defines the width of the texture
  14804. * @param height defines the height of the texture
  14805. * @param format defines the format of the data
  14806. * @param generateMipMaps defines if the engine should generate the mip levels
  14807. * @param invertY defines if data must be stored with Y axis inverted
  14808. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14809. * @param compression defines the compression used (null by default)
  14810. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14811. * @returns the raw texture inside an InternalTexture
  14812. */
  14813. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14814. if (compression === void 0) { compression = null; }
  14815. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14816. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14817. texture.baseWidth = width;
  14818. texture.baseHeight = height;
  14819. texture.width = width;
  14820. texture.height = height;
  14821. texture.format = format;
  14822. texture.generateMipMaps = generateMipMaps;
  14823. texture.samplingMode = samplingMode;
  14824. texture.invertY = invertY;
  14825. texture._compression = compression;
  14826. texture.type = type;
  14827. if (!this._doNotHandleContextLost) {
  14828. texture._bufferView = data;
  14829. }
  14830. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14831. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14832. // Filters
  14833. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14834. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14835. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14836. if (generateMipMaps) {
  14837. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14838. }
  14839. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14840. this._internalTexturesCache.push(texture);
  14841. return texture;
  14842. };
  14843. /**
  14844. * Creates a dynamic texture
  14845. * @param width defines the width of the texture
  14846. * @param height defines the height of the texture
  14847. * @param generateMipMaps defines if the engine should generate the mip levels
  14848. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14849. * @returns the dynamic texture inside an InternalTexture
  14850. */
  14851. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14852. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14853. texture.baseWidth = width;
  14854. texture.baseHeight = height;
  14855. if (generateMipMaps) {
  14856. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14857. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14858. }
  14859. // this.resetTextureCache();
  14860. texture.width = width;
  14861. texture.height = height;
  14862. texture.isReady = false;
  14863. texture.generateMipMaps = generateMipMaps;
  14864. texture.samplingMode = samplingMode;
  14865. this.updateTextureSamplingMode(samplingMode, texture);
  14866. this._internalTexturesCache.push(texture);
  14867. return texture;
  14868. };
  14869. /**
  14870. * Update the sampling mode of a given texture
  14871. * @param samplingMode defines the required sampling mode
  14872. * @param texture defines the texture to update
  14873. */
  14874. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14875. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14876. if (texture.isCube) {
  14877. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14878. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14879. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14880. }
  14881. else if (texture.is3D) {
  14882. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14883. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14884. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14885. }
  14886. else {
  14887. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14888. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14889. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14890. }
  14891. texture.samplingMode = samplingMode;
  14892. };
  14893. /**
  14894. * Update the content of a dynamic texture
  14895. * @param texture defines the texture to update
  14896. * @param canvas defines the canvas containing the source
  14897. * @param invertY defines if data must be stored with Y axis inverted
  14898. * @param premulAlpha defines if alpha is stored as premultiplied
  14899. * @param format defines the format of the data
  14900. */
  14901. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14902. if (premulAlpha === void 0) { premulAlpha = false; }
  14903. if (!texture) {
  14904. return;
  14905. }
  14906. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14907. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14908. if (premulAlpha) {
  14909. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14910. }
  14911. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14912. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14913. if (texture.generateMipMaps) {
  14914. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14915. }
  14916. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14917. if (premulAlpha) {
  14918. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14919. }
  14920. texture.isReady = true;
  14921. };
  14922. /**
  14923. * Update a video texture
  14924. * @param texture defines the texture to update
  14925. * @param video defines the video element to use
  14926. * @param invertY defines if data must be stored with Y axis inverted
  14927. */
  14928. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14929. if (!texture || texture._isDisabled) {
  14930. return;
  14931. }
  14932. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14933. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14934. try {
  14935. // Testing video texture support
  14936. if (this._videoTextureSupported === undefined) {
  14937. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14938. if (this._gl.getError() !== 0) {
  14939. this._videoTextureSupported = false;
  14940. }
  14941. else {
  14942. this._videoTextureSupported = true;
  14943. }
  14944. }
  14945. // Copy video through the current working canvas if video texture is not supported
  14946. if (!this._videoTextureSupported) {
  14947. if (!texture._workingCanvas) {
  14948. texture._workingCanvas = document.createElement("canvas");
  14949. var context = texture._workingCanvas.getContext("2d");
  14950. if (!context) {
  14951. throw new Error("Unable to get 2d context");
  14952. }
  14953. texture._workingContext = context;
  14954. texture._workingCanvas.width = texture.width;
  14955. texture._workingCanvas.height = texture.height;
  14956. }
  14957. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14958. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14959. }
  14960. else {
  14961. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14962. }
  14963. if (texture.generateMipMaps) {
  14964. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14965. }
  14966. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14967. // this.resetTextureCache();
  14968. texture.isReady = true;
  14969. }
  14970. catch (ex) {
  14971. // Something unexpected
  14972. // Let's disable the texture
  14973. texture._isDisabled = true;
  14974. }
  14975. };
  14976. /**
  14977. * Updates a depth texture Comparison Mode and Function.
  14978. * If the comparison Function is equal to 0, the mode will be set to none.
  14979. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14980. * @param texture The texture to set the comparison function for
  14981. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14982. */
  14983. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14984. if (this.webGLVersion === 1) {
  14985. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14986. return;
  14987. }
  14988. var gl = this._gl;
  14989. if (texture.isCube) {
  14990. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14991. if (comparisonFunction === 0) {
  14992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14994. }
  14995. else {
  14996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14998. }
  14999. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15000. }
  15001. else {
  15002. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15003. if (comparisonFunction === 0) {
  15004. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15006. }
  15007. else {
  15008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15010. }
  15011. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15012. }
  15013. texture._comparisonFunction = comparisonFunction;
  15014. };
  15015. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15016. var width = size.width || size;
  15017. var height = size.height || size;
  15018. internalTexture.baseWidth = width;
  15019. internalTexture.baseHeight = height;
  15020. internalTexture.width = width;
  15021. internalTexture.height = height;
  15022. internalTexture.isReady = true;
  15023. internalTexture.samples = 1;
  15024. internalTexture.generateMipMaps = false;
  15025. internalTexture._generateDepthBuffer = true;
  15026. internalTexture._generateStencilBuffer = generateStencil;
  15027. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15028. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15029. internalTexture._comparisonFunction = comparisonFunction;
  15030. var gl = this._gl;
  15031. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15032. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15033. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15034. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15035. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15036. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15037. if (comparisonFunction === 0) {
  15038. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15039. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15040. }
  15041. else {
  15042. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15043. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15044. }
  15045. };
  15046. /**
  15047. * Creates a depth stencil texture.
  15048. * This is only available in WebGL 2 or with the depth texture extension available.
  15049. * @param size The size of face edge in the texture.
  15050. * @param options The options defining the texture.
  15051. * @returns The texture
  15052. */
  15053. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15054. if (options.isCube) {
  15055. var width = size.width || size;
  15056. return this._createDepthStencilCubeTexture(width, options);
  15057. }
  15058. else {
  15059. return this._createDepthStencilTexture(size, options);
  15060. }
  15061. };
  15062. /**
  15063. * Creates a depth stencil texture.
  15064. * This is only available in WebGL 2 or with the depth texture extension available.
  15065. * @param size The size of face edge in the texture.
  15066. * @param options The options defining the texture.
  15067. * @returns The texture
  15068. */
  15069. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15070. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15071. if (!this._caps.depthTextureExtension) {
  15072. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15073. return internalTexture;
  15074. }
  15075. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15076. var gl = this._gl;
  15077. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15078. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15079. if (this.webGLVersion > 1) {
  15080. if (internalOptions.generateStencil) {
  15081. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15082. }
  15083. else {
  15084. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15085. }
  15086. }
  15087. else {
  15088. if (internalOptions.generateStencil) {
  15089. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15090. }
  15091. else {
  15092. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15093. }
  15094. }
  15095. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15096. return internalTexture;
  15097. };
  15098. /**
  15099. * Creates a depth stencil cube texture.
  15100. * This is only available in WebGL 2.
  15101. * @param size The size of face edge in the cube texture.
  15102. * @param options The options defining the cube texture.
  15103. * @returns The cube texture
  15104. */
  15105. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15106. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15107. internalTexture.isCube = true;
  15108. if (this.webGLVersion === 1) {
  15109. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15110. return internalTexture;
  15111. }
  15112. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15113. var gl = this._gl;
  15114. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15115. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15116. // Create the depth/stencil buffer
  15117. for (var face = 0; face < 6; face++) {
  15118. if (internalOptions.generateStencil) {
  15119. 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);
  15120. }
  15121. else {
  15122. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15123. }
  15124. }
  15125. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15126. return internalTexture;
  15127. };
  15128. /**
  15129. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15130. * @param renderTarget The render target to set the frame buffer for
  15131. */
  15132. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15133. // Create the framebuffer
  15134. var internalTexture = renderTarget.getInternalTexture();
  15135. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15136. return;
  15137. }
  15138. var gl = this._gl;
  15139. var depthStencilTexture = renderTarget.depthStencilTexture;
  15140. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15141. if (depthStencilTexture.isCube) {
  15142. if (depthStencilTexture._generateStencilBuffer) {
  15143. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15144. }
  15145. else {
  15146. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15147. }
  15148. }
  15149. else {
  15150. if (depthStencilTexture._generateStencilBuffer) {
  15151. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15152. }
  15153. else {
  15154. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15155. }
  15156. }
  15157. this.bindUnboundFramebuffer(null);
  15158. };
  15159. /**
  15160. * Creates a new render target texture
  15161. * @param size defines the size of the texture
  15162. * @param options defines the options used to create the texture
  15163. * @returns a new render target texture stored in an InternalTexture
  15164. */
  15165. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15166. var fullOptions = new RenderTargetCreationOptions();
  15167. if (options !== undefined && typeof options === "object") {
  15168. fullOptions.generateMipMaps = options.generateMipMaps;
  15169. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15170. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15171. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15172. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15173. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15174. }
  15175. else {
  15176. fullOptions.generateMipMaps = options;
  15177. fullOptions.generateDepthBuffer = true;
  15178. fullOptions.generateStencilBuffer = false;
  15179. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15180. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15181. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15182. }
  15183. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15184. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15185. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15186. }
  15187. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15188. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15189. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15190. }
  15191. var gl = this._gl;
  15192. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15193. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15194. var width = size.width || size;
  15195. var height = size.height || size;
  15196. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15197. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15198. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15199. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15200. }
  15201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15204. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15205. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15206. // Create the framebuffer
  15207. var currentFrameBuffer = this._currentFramebuffer;
  15208. var framebuffer = gl.createFramebuffer();
  15209. this.bindUnboundFramebuffer(framebuffer);
  15210. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15211. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15212. if (fullOptions.generateMipMaps) {
  15213. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15214. }
  15215. // Unbind
  15216. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15217. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15218. this.bindUnboundFramebuffer(currentFrameBuffer);
  15219. texture._framebuffer = framebuffer;
  15220. texture.baseWidth = width;
  15221. texture.baseHeight = height;
  15222. texture.width = width;
  15223. texture.height = height;
  15224. texture.isReady = true;
  15225. texture.samples = 1;
  15226. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15227. texture.samplingMode = fullOptions.samplingMode;
  15228. texture.type = fullOptions.type;
  15229. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15230. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15231. // this.resetTextureCache();
  15232. this._internalTexturesCache.push(texture);
  15233. return texture;
  15234. };
  15235. /**
  15236. * Create a multi render target texture
  15237. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15238. * @param size defines the size of the texture
  15239. * @param options defines the creation options
  15240. * @returns the cube texture as an InternalTexture
  15241. */
  15242. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15243. var generateMipMaps = false;
  15244. var generateDepthBuffer = true;
  15245. var generateStencilBuffer = false;
  15246. var generateDepthTexture = false;
  15247. var textureCount = 1;
  15248. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15249. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15250. var types = new Array();
  15251. var samplingModes = new Array();
  15252. if (options !== undefined) {
  15253. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15254. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15255. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15256. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15257. textureCount = options.textureCount || 1;
  15258. if (options.types) {
  15259. types = options.types;
  15260. }
  15261. if (options.samplingModes) {
  15262. samplingModes = options.samplingModes;
  15263. }
  15264. }
  15265. var gl = this._gl;
  15266. // Create the framebuffer
  15267. var framebuffer = gl.createFramebuffer();
  15268. this.bindUnboundFramebuffer(framebuffer);
  15269. var width = size.width || size;
  15270. var height = size.height || size;
  15271. var textures = [];
  15272. var attachments = [];
  15273. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15274. for (var i = 0; i < textureCount; i++) {
  15275. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15276. var type = types[i] || defaultType;
  15277. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15278. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15279. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15280. }
  15281. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15282. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15283. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15284. }
  15285. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15286. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15287. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15288. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15289. }
  15290. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15291. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15292. textures.push(texture);
  15293. attachments.push(attachment);
  15294. gl.activeTexture(gl["TEXTURE" + i]);
  15295. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15300. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15301. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15302. if (generateMipMaps) {
  15303. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15304. }
  15305. // Unbind
  15306. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15307. texture._framebuffer = framebuffer;
  15308. texture._depthStencilBuffer = depthStencilBuffer;
  15309. texture.baseWidth = width;
  15310. texture.baseHeight = height;
  15311. texture.width = width;
  15312. texture.height = height;
  15313. texture.isReady = true;
  15314. texture.samples = 1;
  15315. texture.generateMipMaps = generateMipMaps;
  15316. texture.samplingMode = samplingMode;
  15317. texture.type = type;
  15318. texture._generateDepthBuffer = generateDepthBuffer;
  15319. texture._generateStencilBuffer = generateStencilBuffer;
  15320. texture._attachments = attachments;
  15321. this._internalTexturesCache.push(texture);
  15322. }
  15323. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15324. // Depth texture
  15325. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15326. gl.activeTexture(gl.TEXTURE0);
  15327. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15329. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15330. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15331. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15332. 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);
  15333. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15334. depthTexture._framebuffer = framebuffer;
  15335. depthTexture.baseWidth = width;
  15336. depthTexture.baseHeight = height;
  15337. depthTexture.width = width;
  15338. depthTexture.height = height;
  15339. depthTexture.isReady = true;
  15340. depthTexture.samples = 1;
  15341. depthTexture.generateMipMaps = generateMipMaps;
  15342. depthTexture.samplingMode = gl.NEAREST;
  15343. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15344. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15345. textures.push(depthTexture);
  15346. this._internalTexturesCache.push(depthTexture);
  15347. }
  15348. gl.drawBuffers(attachments);
  15349. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15350. this.bindUnboundFramebuffer(null);
  15351. this.resetTextureCache();
  15352. return textures;
  15353. };
  15354. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15355. if (samples === void 0) { samples = 1; }
  15356. var depthStencilBuffer = null;
  15357. var gl = this._gl;
  15358. // Create the depth/stencil buffer
  15359. if (generateStencilBuffer) {
  15360. depthStencilBuffer = gl.createRenderbuffer();
  15361. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15362. if (samples > 1) {
  15363. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15364. }
  15365. else {
  15366. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15367. }
  15368. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15369. }
  15370. else if (generateDepthBuffer) {
  15371. depthStencilBuffer = gl.createRenderbuffer();
  15372. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15373. if (samples > 1) {
  15374. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15375. }
  15376. else {
  15377. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15378. }
  15379. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15380. }
  15381. return depthStencilBuffer;
  15382. };
  15383. /**
  15384. * Updates the sample count of a render target texture
  15385. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15386. * @param texture defines the texture to update
  15387. * @param samples defines the sample count to set
  15388. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15389. */
  15390. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15391. if (this.webGLVersion < 2 || !texture) {
  15392. return 1;
  15393. }
  15394. if (texture.samples === samples) {
  15395. return samples;
  15396. }
  15397. var gl = this._gl;
  15398. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15399. // Dispose previous render buffers
  15400. if (texture._depthStencilBuffer) {
  15401. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15402. texture._depthStencilBuffer = null;
  15403. }
  15404. if (texture._MSAAFramebuffer) {
  15405. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15406. texture._MSAAFramebuffer = null;
  15407. }
  15408. if (texture._MSAARenderBuffer) {
  15409. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15410. texture._MSAARenderBuffer = null;
  15411. }
  15412. if (samples > 1) {
  15413. var framebuffer = gl.createFramebuffer();
  15414. if (!framebuffer) {
  15415. throw new Error("Unable to create multi sampled framebuffer");
  15416. }
  15417. texture._MSAAFramebuffer = framebuffer;
  15418. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15419. var colorRenderbuffer = gl.createRenderbuffer();
  15420. if (!colorRenderbuffer) {
  15421. throw new Error("Unable to create multi sampled framebuffer");
  15422. }
  15423. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15424. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15425. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15426. texture._MSAARenderBuffer = colorRenderbuffer;
  15427. }
  15428. else {
  15429. this.bindUnboundFramebuffer(texture._framebuffer);
  15430. }
  15431. texture.samples = samples;
  15432. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15433. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15434. this.bindUnboundFramebuffer(null);
  15435. return samples;
  15436. };
  15437. /**
  15438. * Update the sample count for a given multiple render target texture
  15439. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15440. * @param textures defines the textures to update
  15441. * @param samples defines the sample count to set
  15442. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15443. */
  15444. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15445. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15446. return 1;
  15447. }
  15448. if (textures[0].samples === samples) {
  15449. return samples;
  15450. }
  15451. var gl = this._gl;
  15452. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15453. // Dispose previous render buffers
  15454. if (textures[0]._depthStencilBuffer) {
  15455. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15456. textures[0]._depthStencilBuffer = null;
  15457. }
  15458. if (textures[0]._MSAAFramebuffer) {
  15459. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15460. textures[0]._MSAAFramebuffer = null;
  15461. }
  15462. for (var i = 0; i < textures.length; i++) {
  15463. if (textures[i]._MSAARenderBuffer) {
  15464. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15465. textures[i]._MSAARenderBuffer = null;
  15466. }
  15467. }
  15468. if (samples > 1) {
  15469. var framebuffer = gl.createFramebuffer();
  15470. if (!framebuffer) {
  15471. throw new Error("Unable to create multi sampled framebuffer");
  15472. }
  15473. this.bindUnboundFramebuffer(framebuffer);
  15474. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15475. var attachments = [];
  15476. for (var i = 0; i < textures.length; i++) {
  15477. var texture = textures[i];
  15478. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15479. var colorRenderbuffer = gl.createRenderbuffer();
  15480. if (!colorRenderbuffer) {
  15481. throw new Error("Unable to create multi sampled framebuffer");
  15482. }
  15483. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15484. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15485. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15486. texture._MSAAFramebuffer = framebuffer;
  15487. texture._MSAARenderBuffer = colorRenderbuffer;
  15488. texture.samples = samples;
  15489. texture._depthStencilBuffer = depthStencilBuffer;
  15490. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15491. attachments.push(attachment);
  15492. }
  15493. gl.drawBuffers(attachments);
  15494. }
  15495. else {
  15496. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15497. }
  15498. this.bindUnboundFramebuffer(null);
  15499. return samples;
  15500. };
  15501. /** @hidden */
  15502. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15503. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15504. };
  15505. /** @hidden */
  15506. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15507. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15508. };
  15509. /** @hidden */
  15510. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15511. var gl = this._gl;
  15512. var textureType = this._getWebGLTextureType(texture.type);
  15513. var format = this._getInternalFormat(texture.format);
  15514. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15515. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15516. this._bindTextureDirectly(bindTarget, texture, true);
  15517. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15518. var target = gl.TEXTURE_2D;
  15519. if (texture.isCube) {
  15520. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15521. }
  15522. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15523. this._bindTextureDirectly(bindTarget, null, true);
  15524. };
  15525. /**
  15526. * Creates a new render target cube texture
  15527. * @param size defines the size of the texture
  15528. * @param options defines the options used to create the texture
  15529. * @returns a new render target cube texture stored in an InternalTexture
  15530. */
  15531. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15532. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15533. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15534. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15535. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15536. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15537. }
  15538. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15539. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15540. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15541. }
  15542. var gl = this._gl;
  15543. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15544. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15545. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15546. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15547. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15548. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15549. }
  15550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15552. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15553. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15554. for (var face = 0; face < 6; face++) {
  15555. 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);
  15556. }
  15557. // Create the framebuffer
  15558. var framebuffer = gl.createFramebuffer();
  15559. this.bindUnboundFramebuffer(framebuffer);
  15560. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15561. // MipMaps
  15562. if (fullOptions.generateMipMaps) {
  15563. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15564. }
  15565. // Unbind
  15566. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15567. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15568. this.bindUnboundFramebuffer(null);
  15569. texture._framebuffer = framebuffer;
  15570. texture.width = size;
  15571. texture.height = size;
  15572. texture.isReady = true;
  15573. texture.isCube = true;
  15574. texture.samples = 1;
  15575. texture.generateMipMaps = fullOptions.generateMipMaps;
  15576. texture.samplingMode = fullOptions.samplingMode;
  15577. texture.type = fullOptions.type;
  15578. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15579. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15580. this._internalTexturesCache.push(texture);
  15581. return texture;
  15582. };
  15583. /**
  15584. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15585. * @param rootUrl defines the url where the file to load is located
  15586. * @param scene defines the current scene
  15587. * @param lodScale defines scale to apply to the mip map selection
  15588. * @param lodOffset defines offset to apply to the mip map selection
  15589. * @param onLoad defines an optional callback raised when the texture is loaded
  15590. * @param onError defines an optional callback raised if there is an issue to load the texture
  15591. * @param format defines the format of the data
  15592. * @param forcedExtension defines the extension to use to pick the right loader
  15593. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15594. * @returns the cube texture as an InternalTexture
  15595. */
  15596. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15597. var _this = this;
  15598. if (onLoad === void 0) { onLoad = null; }
  15599. if (onError === void 0) { onError = null; }
  15600. if (forcedExtension === void 0) { forcedExtension = null; }
  15601. if (createPolynomials === void 0) { createPolynomials = true; }
  15602. var callback = function (loadData) {
  15603. if (!loadData) {
  15604. if (onLoad) {
  15605. onLoad(null);
  15606. }
  15607. return;
  15608. }
  15609. var texture = loadData.texture;
  15610. if (!createPolynomials) {
  15611. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15612. }
  15613. else if (loadData.info.sphericalPolynomial) {
  15614. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15615. }
  15616. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15617. if (_this._caps.textureLOD) {
  15618. // Do not add extra process if texture lod is supported.
  15619. if (onLoad) {
  15620. onLoad(texture);
  15621. }
  15622. return;
  15623. }
  15624. var mipSlices = 3;
  15625. var gl = _this._gl;
  15626. var width = loadData.width;
  15627. if (!width) {
  15628. return;
  15629. }
  15630. var textures = [];
  15631. for (var i = 0; i < mipSlices; i++) {
  15632. //compute LOD from even spacing in smoothness (matching shader calculation)
  15633. var smoothness = i / (mipSlices - 1);
  15634. var roughness = 1 - smoothness;
  15635. var minLODIndex = lodOffset; // roughness = 0
  15636. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15637. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15638. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15639. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15640. glTextureFromLod.isCube = true;
  15641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15646. if (loadData.isDDS) {
  15647. var info = loadData.info;
  15648. var data = loadData.data;
  15649. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15650. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15651. }
  15652. else {
  15653. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15654. }
  15655. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15656. // Wrap in a base texture for easy binding.
  15657. var lodTexture = new BABYLON.BaseTexture(scene);
  15658. lodTexture.isCube = true;
  15659. lodTexture._texture = glTextureFromLod;
  15660. glTextureFromLod.isReady = true;
  15661. textures.push(lodTexture);
  15662. }
  15663. texture._lodTextureHigh = textures[2];
  15664. texture._lodTextureMid = textures[1];
  15665. texture._lodTextureLow = textures[0];
  15666. if (onLoad) {
  15667. onLoad(texture);
  15668. }
  15669. };
  15670. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15671. };
  15672. /**
  15673. * Creates a cube texture
  15674. * @param rootUrl defines the url where the files to load is located
  15675. * @param scene defines the current scene
  15676. * @param files defines the list of files to load (1 per face)
  15677. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15678. * @param onLoad defines an optional callback raised when the texture is loaded
  15679. * @param onError defines an optional callback raised if there is an issue to load the texture
  15680. * @param format defines the format of the data
  15681. * @param forcedExtension defines the extension to use to pick the right loader
  15682. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15683. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15684. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15685. * @returns the cube texture as an InternalTexture
  15686. */
  15687. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15688. var _this = this;
  15689. if (onLoad === void 0) { onLoad = null; }
  15690. if (onError === void 0) { onError = null; }
  15691. if (forcedExtension === void 0) { forcedExtension = null; }
  15692. if (createPolynomials === void 0) { createPolynomials = false; }
  15693. if (lodScale === void 0) { lodScale = 0; }
  15694. if (lodOffset === void 0) { lodOffset = 0; }
  15695. var gl = this._gl;
  15696. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15697. texture.isCube = true;
  15698. texture.url = rootUrl;
  15699. texture.generateMipMaps = !noMipmap;
  15700. texture._lodGenerationScale = lodScale;
  15701. texture._lodGenerationOffset = lodOffset;
  15702. if (!this._doNotHandleContextLost) {
  15703. texture._extension = forcedExtension;
  15704. texture._files = files;
  15705. }
  15706. var isKTX = false;
  15707. var isDDS = false;
  15708. var isEnv = false;
  15709. var lastDot = rootUrl.lastIndexOf('.');
  15710. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15711. if (this._textureFormatInUse) {
  15712. extension = this._textureFormatInUse;
  15713. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15714. isKTX = true;
  15715. }
  15716. else {
  15717. isDDS = (extension === ".dds");
  15718. isEnv = (extension === ".env");
  15719. }
  15720. var onerror = function (request, exception) {
  15721. if (onError && request) {
  15722. onError(request.status + " " + request.statusText, exception);
  15723. }
  15724. };
  15725. if (isKTX) {
  15726. this._loadFile(rootUrl, function (data) {
  15727. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15728. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15729. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15730. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15731. ktx.uploadLevels(_this._gl, !noMipmap);
  15732. _this.setCubeMapTextureParams(gl, loadMipmap);
  15733. texture.width = ktx.pixelWidth;
  15734. texture.height = ktx.pixelHeight;
  15735. texture.isReady = true;
  15736. }, undefined, undefined, true, onerror);
  15737. }
  15738. else if (isEnv) {
  15739. this._loadFile(rootUrl, function (data) {
  15740. data = data;
  15741. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15742. if (info) {
  15743. texture.width = info.width;
  15744. texture.height = info.width;
  15745. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15746. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15747. texture.isReady = true;
  15748. if (onLoad) {
  15749. onLoad();
  15750. }
  15751. });
  15752. }
  15753. else if (onError) {
  15754. onError("Can not parse the environment file", null);
  15755. }
  15756. }, undefined, undefined, true, onerror);
  15757. }
  15758. else if (isDDS) {
  15759. if (files && files.length === 6) {
  15760. this._cascadeLoadFiles(scene, function (imgs) {
  15761. var info;
  15762. var loadMipmap = false;
  15763. var width = 0;
  15764. for (var index = 0; index < imgs.length; index++) {
  15765. var data = imgs[index];
  15766. info = BABYLON.DDSTools.GetDDSInfo(data);
  15767. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15768. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15769. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15770. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15771. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15772. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15773. }
  15774. texture.width = info.width;
  15775. texture.height = info.height;
  15776. texture.type = info.textureType;
  15777. width = info.width;
  15778. }
  15779. _this.setCubeMapTextureParams(gl, loadMipmap);
  15780. texture.isReady = true;
  15781. if (onLoad) {
  15782. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15783. }
  15784. }, files, onError);
  15785. }
  15786. else {
  15787. this._loadFile(rootUrl, function (data) {
  15788. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15789. if (createPolynomials) {
  15790. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15791. }
  15792. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15793. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15794. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15795. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15796. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15797. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15798. }
  15799. _this.setCubeMapTextureParams(gl, loadMipmap);
  15800. texture.width = info.width;
  15801. texture.height = info.height;
  15802. texture.isReady = true;
  15803. texture.type = info.textureType;
  15804. if (onLoad) {
  15805. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15806. }
  15807. }, undefined, undefined, true, onerror);
  15808. }
  15809. }
  15810. else {
  15811. if (!files) {
  15812. throw new Error("Cannot load cubemap because files were not defined");
  15813. }
  15814. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15815. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15816. var height = width;
  15817. _this._prepareWorkingCanvas();
  15818. if (!_this._workingCanvas || !_this._workingContext) {
  15819. return;
  15820. }
  15821. _this._workingCanvas.width = width;
  15822. _this._workingCanvas.height = height;
  15823. var faces = [
  15824. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15825. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15826. ];
  15827. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15829. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15830. for (var index = 0; index < faces.length; index++) {
  15831. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15832. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15833. }
  15834. if (!noMipmap) {
  15835. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15836. }
  15837. _this.setCubeMapTextureParams(gl, !noMipmap);
  15838. texture.width = width;
  15839. texture.height = height;
  15840. texture.isReady = true;
  15841. if (format) {
  15842. texture.format = format;
  15843. }
  15844. texture.onLoadedObservable.notifyObservers(texture);
  15845. texture.onLoadedObservable.clear();
  15846. if (onLoad) {
  15847. onLoad();
  15848. }
  15849. }, files, onError);
  15850. }
  15851. this._internalTexturesCache.push(texture);
  15852. return texture;
  15853. };
  15854. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15860. // this.resetTextureCache();
  15861. };
  15862. /**
  15863. * Update a raw cube texture
  15864. * @param texture defines the texture to udpdate
  15865. * @param data defines the data to store
  15866. * @param format defines the data format
  15867. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15868. * @param invertY defines if data must be stored with Y axis inverted
  15869. * @param compression defines the compression used (null by default)
  15870. * @param level defines which level of the texture to update
  15871. */
  15872. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15873. if (compression === void 0) { compression = null; }
  15874. if (level === void 0) { level = 0; }
  15875. texture._bufferViewArray = data;
  15876. texture.format = format;
  15877. texture.type = type;
  15878. texture.invertY = invertY;
  15879. texture._compression = compression;
  15880. var gl = this._gl;
  15881. var textureType = this._getWebGLTextureType(type);
  15882. var internalFormat = this._getInternalFormat(format);
  15883. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15884. var needConversion = false;
  15885. if (internalFormat === gl.RGB) {
  15886. internalFormat = gl.RGBA;
  15887. needConversion = true;
  15888. }
  15889. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15891. if (texture.width % 4 !== 0) {
  15892. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15893. }
  15894. // Data are known to be in +X +Y +Z -X -Y -Z
  15895. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15896. var faceData = data[faceIndex];
  15897. if (compression) {
  15898. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15899. }
  15900. else {
  15901. if (needConversion) {
  15902. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15903. }
  15904. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15905. }
  15906. }
  15907. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15908. if (isPot && texture.generateMipMaps && level === 0) {
  15909. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15910. }
  15911. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15912. // this.resetTextureCache();
  15913. texture.isReady = true;
  15914. };
  15915. /**
  15916. * Creates a new raw cube texture
  15917. * @param data defines the array of data to use to create each face
  15918. * @param size defines the size of the textures
  15919. * @param format defines the format of the data
  15920. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15921. * @param generateMipMaps defines if the engine should generate the mip levels
  15922. * @param invertY defines if data must be stored with Y axis inverted
  15923. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15924. * @param compression defines the compression used (null by default)
  15925. * @returns the cube texture as an InternalTexture
  15926. */
  15927. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15928. if (compression === void 0) { compression = null; }
  15929. var gl = this._gl;
  15930. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15931. texture.isCube = true;
  15932. texture.generateMipMaps = generateMipMaps;
  15933. texture.format = format;
  15934. texture.type = type;
  15935. if (!this._doNotHandleContextLost) {
  15936. texture._bufferViewArray = data;
  15937. }
  15938. var textureType = this._getWebGLTextureType(type);
  15939. var internalFormat = this._getInternalFormat(format);
  15940. if (internalFormat === gl.RGB) {
  15941. internalFormat = gl.RGBA;
  15942. }
  15943. var width = size;
  15944. var height = width;
  15945. texture.width = width;
  15946. texture.height = height;
  15947. // Double check on POT to generate Mips.
  15948. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15949. if (!isPot) {
  15950. generateMipMaps = false;
  15951. }
  15952. // Upload data if needed. The texture won't be ready until then.
  15953. if (data) {
  15954. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15955. }
  15956. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15957. // Filters
  15958. if (data && generateMipMaps) {
  15959. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15960. }
  15961. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15964. }
  15965. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15968. }
  15969. else {
  15970. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15971. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15972. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15973. }
  15974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15975. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15976. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15977. return texture;
  15978. };
  15979. /**
  15980. * Creates a new raw cube texture from a specified url
  15981. * @param url defines the url where the data is located
  15982. * @param scene defines the current scene
  15983. * @param size defines the size of the textures
  15984. * @param format defines the format of the data
  15985. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15986. * @param noMipmap defines if the engine should avoid generating the mip levels
  15987. * @param callback defines a callback used to extract texture data from loaded data
  15988. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15989. * @param onLoad defines a callback called when texture is loaded
  15990. * @param onError defines a callback called if there is an error
  15991. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15992. * @param invertY defines if data must be stored with Y axis inverted
  15993. * @returns the cube texture as an InternalTexture
  15994. */
  15995. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15996. var _this = this;
  15997. if (onLoad === void 0) { onLoad = null; }
  15998. if (onError === void 0) { onError = null; }
  15999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16000. if (invertY === void 0) { invertY = false; }
  16001. var gl = this._gl;
  16002. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16003. scene._addPendingData(texture);
  16004. texture.url = url;
  16005. this._internalTexturesCache.push(texture);
  16006. var onerror = function (request, exception) {
  16007. scene._removePendingData(texture);
  16008. if (onError && request) {
  16009. onError(request.status + " " + request.statusText, exception);
  16010. }
  16011. };
  16012. var internalCallback = function (data) {
  16013. var width = texture.width;
  16014. var faceDataArrays = callback(data);
  16015. if (!faceDataArrays) {
  16016. return;
  16017. }
  16018. if (mipmapGenerator) {
  16019. var textureType = _this._getWebGLTextureType(type);
  16020. var internalFormat = _this._getInternalFormat(format);
  16021. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16022. var needConversion = false;
  16023. if (internalFormat === gl.RGB) {
  16024. internalFormat = gl.RGBA;
  16025. needConversion = true;
  16026. }
  16027. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16028. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16029. var mipData = mipmapGenerator(faceDataArrays);
  16030. for (var level = 0; level < mipData.length; level++) {
  16031. var mipSize = width >> level;
  16032. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16033. var mipFaceData = mipData[level][faceIndex];
  16034. if (needConversion) {
  16035. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16036. }
  16037. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16038. }
  16039. }
  16040. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16041. }
  16042. else {
  16043. texture.generateMipMaps = !noMipmap;
  16044. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16045. }
  16046. texture.isReady = true;
  16047. // this.resetTextureCache();
  16048. scene._removePendingData(texture);
  16049. if (onLoad) {
  16050. onLoad();
  16051. }
  16052. };
  16053. this._loadFile(url, function (data) {
  16054. internalCallback(data);
  16055. }, undefined, scene.database, true, onerror);
  16056. return texture;
  16057. };
  16058. ;
  16059. /**
  16060. * Update a raw 3D texture
  16061. * @param texture defines the texture to update
  16062. * @param data defines the data to store
  16063. * @param format defines the data format
  16064. * @param invertY defines if data must be stored with Y axis inverted
  16065. * @param compression defines the used compression (can be null)
  16066. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16067. */
  16068. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16069. if (compression === void 0) { compression = null; }
  16070. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16071. var internalType = this._getWebGLTextureType(textureType);
  16072. var internalFormat = this._getInternalFormat(format);
  16073. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16074. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16075. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16076. if (!this._doNotHandleContextLost) {
  16077. texture._bufferView = data;
  16078. texture.format = format;
  16079. texture.invertY = invertY;
  16080. texture._compression = compression;
  16081. }
  16082. if (texture.width % 4 !== 0) {
  16083. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16084. }
  16085. if (compression && data) {
  16086. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16087. }
  16088. else {
  16089. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16090. }
  16091. if (texture.generateMipMaps) {
  16092. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16093. }
  16094. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16095. // this.resetTextureCache();
  16096. texture.isReady = true;
  16097. };
  16098. /**
  16099. * Creates a new raw 3D texture
  16100. * @param data defines the data used to create the texture
  16101. * @param width defines the width of the texture
  16102. * @param height defines the height of the texture
  16103. * @param depth defines the depth of the texture
  16104. * @param format defines the format of the texture
  16105. * @param generateMipMaps defines if the engine must generate mip levels
  16106. * @param invertY defines if data must be stored with Y axis inverted
  16107. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16108. * @param compression defines the compressed used (can be null)
  16109. * @param textureType defines the compressed used (can be null)
  16110. * @returns a new raw 3D texture (stored in an InternalTexture)
  16111. */
  16112. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16113. if (compression === void 0) { compression = null; }
  16114. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16115. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16116. texture.baseWidth = width;
  16117. texture.baseHeight = height;
  16118. texture.baseDepth = depth;
  16119. texture.width = width;
  16120. texture.height = height;
  16121. texture.depth = depth;
  16122. texture.format = format;
  16123. texture.type = textureType;
  16124. texture.generateMipMaps = generateMipMaps;
  16125. texture.samplingMode = samplingMode;
  16126. texture.is3D = true;
  16127. if (!this._doNotHandleContextLost) {
  16128. texture._bufferView = data;
  16129. }
  16130. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16131. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16132. // Filters
  16133. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16134. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16135. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16136. if (generateMipMaps) {
  16137. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16138. }
  16139. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16140. this._internalTexturesCache.push(texture);
  16141. return texture;
  16142. };
  16143. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16144. var gl = this._gl;
  16145. if (!gl) {
  16146. return;
  16147. }
  16148. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16149. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16151. if (!noMipmap && !isCompressed) {
  16152. gl.generateMipmap(gl.TEXTURE_2D);
  16153. }
  16154. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16155. // this.resetTextureCache();
  16156. if (scene) {
  16157. scene._removePendingData(texture);
  16158. }
  16159. texture.onLoadedObservable.notifyObservers(texture);
  16160. texture.onLoadedObservable.clear();
  16161. };
  16162. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16163. var _this = this;
  16164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16165. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16166. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16167. var gl = this._gl;
  16168. if (!gl) {
  16169. return;
  16170. }
  16171. if (!texture._webGLTexture) {
  16172. // this.resetTextureCache();
  16173. if (scene) {
  16174. scene._removePendingData(texture);
  16175. }
  16176. return;
  16177. }
  16178. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16179. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16180. texture.baseWidth = width;
  16181. texture.baseHeight = height;
  16182. texture.width = potWidth;
  16183. texture.height = potHeight;
  16184. texture.isReady = true;
  16185. if (processFunction(potWidth, potHeight, function () {
  16186. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16187. })) {
  16188. // Returning as texture needs extra async steps
  16189. return;
  16190. }
  16191. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16192. };
  16193. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16194. // Create new RGBA data container.
  16195. var rgbaData;
  16196. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16197. rgbaData = new Float32Array(width * height * 4);
  16198. }
  16199. else {
  16200. rgbaData = new Uint32Array(width * height * 4);
  16201. }
  16202. // Convert each pixel.
  16203. for (var x = 0; x < width; x++) {
  16204. for (var y = 0; y < height; y++) {
  16205. var index = (y * width + x) * 3;
  16206. var newIndex = (y * width + x) * 4;
  16207. // Map Old Value to new value.
  16208. rgbaData[newIndex + 0] = rgbData[index + 0];
  16209. rgbaData[newIndex + 1] = rgbData[index + 1];
  16210. rgbaData[newIndex + 2] = rgbData[index + 2];
  16211. // Add fully opaque alpha channel.
  16212. rgbaData[newIndex + 3] = 1;
  16213. }
  16214. }
  16215. return rgbaData;
  16216. };
  16217. /** @hidden */
  16218. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16219. var gl = this._gl;
  16220. if (texture._framebuffer) {
  16221. gl.deleteFramebuffer(texture._framebuffer);
  16222. texture._framebuffer = null;
  16223. }
  16224. if (texture._depthStencilBuffer) {
  16225. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16226. texture._depthStencilBuffer = null;
  16227. }
  16228. if (texture._MSAAFramebuffer) {
  16229. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16230. texture._MSAAFramebuffer = null;
  16231. }
  16232. if (texture._MSAARenderBuffer) {
  16233. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16234. texture._MSAARenderBuffer = null;
  16235. }
  16236. };
  16237. /** @hidden */
  16238. Engine.prototype._releaseTexture = function (texture) {
  16239. var gl = this._gl;
  16240. this._releaseFramebufferObjects(texture);
  16241. gl.deleteTexture(texture._webGLTexture);
  16242. // Unbind channels
  16243. this.unbindAllTextures();
  16244. var index = this._internalTexturesCache.indexOf(texture);
  16245. if (index !== -1) {
  16246. this._internalTexturesCache.splice(index, 1);
  16247. }
  16248. // Integrated fixed lod samplers.
  16249. if (texture._lodTextureHigh) {
  16250. texture._lodTextureHigh.dispose();
  16251. }
  16252. if (texture._lodTextureMid) {
  16253. texture._lodTextureMid.dispose();
  16254. }
  16255. if (texture._lodTextureLow) {
  16256. texture._lodTextureLow.dispose();
  16257. }
  16258. // Set output texture of post process to null if the texture has been released/disposed
  16259. this.scenes.forEach(function (scene) {
  16260. scene.postProcesses.forEach(function (postProcess) {
  16261. if (postProcess._outputTexture == texture) {
  16262. postProcess._outputTexture = null;
  16263. }
  16264. });
  16265. scene.cameras.forEach(function (camera) {
  16266. camera._postProcesses.forEach(function (postProcess) {
  16267. if (postProcess) {
  16268. if (postProcess._outputTexture == texture) {
  16269. postProcess._outputTexture = null;
  16270. }
  16271. }
  16272. });
  16273. });
  16274. });
  16275. };
  16276. Engine.prototype.setProgram = function (program) {
  16277. if (this._currentProgram !== program) {
  16278. this._gl.useProgram(program);
  16279. this._currentProgram = program;
  16280. }
  16281. };
  16282. /**
  16283. * Binds an effect to the webGL context
  16284. * @param effect defines the effect to bind
  16285. */
  16286. Engine.prototype.bindSamplers = function (effect) {
  16287. this.setProgram(effect.getProgram());
  16288. var samplers = effect.getSamplers();
  16289. for (var index = 0; index < samplers.length; index++) {
  16290. var uniform = effect.getUniform(samplers[index]);
  16291. if (uniform) {
  16292. this._boundUniforms[index] = uniform;
  16293. }
  16294. }
  16295. this._currentEffect = null;
  16296. };
  16297. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16298. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16299. return;
  16300. }
  16301. // Remove
  16302. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16303. // Bind last to it
  16304. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16305. // Bind to dummy
  16306. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16307. };
  16308. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16309. if (!internalTexture) {
  16310. return -1;
  16311. }
  16312. internalTexture._initialSlot = channel;
  16313. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16314. if (channel !== internalTexture._designatedSlot) {
  16315. this._textureCollisions.addCount(1, false);
  16316. }
  16317. }
  16318. else {
  16319. if (channel !== internalTexture._designatedSlot) {
  16320. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16321. return internalTexture._designatedSlot;
  16322. }
  16323. else {
  16324. // No slot for this texture, let's pick a new one (if we find a free slot)
  16325. if (this._nextFreeTextureSlots.length) {
  16326. return this._nextFreeTextureSlots[0];
  16327. }
  16328. // We need to recycle the oldest bound texture, sorry.
  16329. this._textureCollisions.addCount(1, false);
  16330. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16331. }
  16332. }
  16333. }
  16334. return channel;
  16335. };
  16336. Engine.prototype._linkTrackers = function (previous, next) {
  16337. previous.next = next;
  16338. next.previous = previous;
  16339. };
  16340. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16341. var currentSlot = internalTexture._designatedSlot;
  16342. if (currentSlot === -1) {
  16343. return -1;
  16344. }
  16345. internalTexture._designatedSlot = -1;
  16346. if (this.disableTextureBindingOptimization) {
  16347. return -1;
  16348. }
  16349. // Remove from bound list
  16350. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16351. // Free the slot
  16352. this._boundTexturesCache[currentSlot] = null;
  16353. this._nextFreeTextureSlots.push(currentSlot);
  16354. return currentSlot;
  16355. };
  16356. Engine.prototype._activateCurrentTexture = function () {
  16357. if (this._currentTextureChannel !== this._activeChannel) {
  16358. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16359. this._currentTextureChannel = this._activeChannel;
  16360. }
  16361. };
  16362. /** @hidden */
  16363. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16364. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16365. if (force === void 0) { force = false; }
  16366. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16367. this._activeChannel = texture._designatedSlot;
  16368. }
  16369. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16370. var isTextureForRendering = texture && texture._initialSlot > -1;
  16371. if (currentTextureBound !== texture || force) {
  16372. if (currentTextureBound) {
  16373. this._removeDesignatedSlot(currentTextureBound);
  16374. }
  16375. this._activateCurrentTexture();
  16376. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16377. this._boundTexturesCache[this._activeChannel] = texture;
  16378. if (texture) {
  16379. if (!this.disableTextureBindingOptimization) {
  16380. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16381. if (slotIndex > -1) {
  16382. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16383. }
  16384. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16385. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16386. }
  16387. texture._designatedSlot = this._activeChannel;
  16388. }
  16389. }
  16390. else if (forTextureDataUpdate) {
  16391. this._activateCurrentTexture();
  16392. }
  16393. if (isTextureForRendering && !forTextureDataUpdate) {
  16394. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16395. }
  16396. };
  16397. /** @hidden */
  16398. Engine.prototype._bindTexture = function (channel, texture) {
  16399. if (channel < 0) {
  16400. return;
  16401. }
  16402. if (texture) {
  16403. channel = this._getCorrectTextureChannel(channel, texture);
  16404. }
  16405. this._activeChannel = channel;
  16406. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16407. };
  16408. /**
  16409. * Sets a texture to the webGL context from a postprocess
  16410. * @param channel defines the channel to use
  16411. * @param postProcess defines the source postprocess
  16412. */
  16413. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16414. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16415. };
  16416. /**
  16417. * Binds the output of the passed in post process to the texture channel specified
  16418. * @param channel The channel the texture should be bound to
  16419. * @param postProcess The post process which's output should be bound
  16420. */
  16421. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16422. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16423. };
  16424. /**
  16425. * Unbind all textures from the webGL context
  16426. */
  16427. Engine.prototype.unbindAllTextures = function () {
  16428. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16429. this._activeChannel = channel;
  16430. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16431. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16432. if (this.webGLVersion > 1) {
  16433. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16434. }
  16435. }
  16436. };
  16437. /**
  16438. * Sets a texture to the according uniform.
  16439. * @param channel The texture channel
  16440. * @param uniform The uniform to set
  16441. * @param texture The texture to apply
  16442. */
  16443. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16444. if (channel < 0) {
  16445. return;
  16446. }
  16447. if (uniform) {
  16448. this._boundUniforms[channel] = uniform;
  16449. }
  16450. this._setTexture(channel, texture);
  16451. };
  16452. /**
  16453. * Sets a depth stencil texture from a render target to the according uniform.
  16454. * @param channel The texture channel
  16455. * @param uniform The uniform to set
  16456. * @param texture The render target texture containing the depth stencil texture to apply
  16457. */
  16458. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16459. if (channel < 0) {
  16460. return;
  16461. }
  16462. if (uniform) {
  16463. this._boundUniforms[channel] = uniform;
  16464. }
  16465. if (!texture || !texture.depthStencilTexture) {
  16466. this._setTexture(channel, null);
  16467. }
  16468. else {
  16469. this._setTexture(channel, texture, false, true);
  16470. }
  16471. };
  16472. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16473. var uniform = this._boundUniforms[sourceSlot];
  16474. if (uniform._currentState === destination) {
  16475. return;
  16476. }
  16477. this._gl.uniform1i(uniform, destination);
  16478. uniform._currentState = destination;
  16479. };
  16480. Engine.prototype._getTextureWrapMode = function (mode) {
  16481. switch (mode) {
  16482. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16483. return this._gl.REPEAT;
  16484. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16485. return this._gl.CLAMP_TO_EDGE;
  16486. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16487. return this._gl.MIRRORED_REPEAT;
  16488. }
  16489. return this._gl.REPEAT;
  16490. };
  16491. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16492. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16493. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16494. // Not ready?
  16495. if (!texture) {
  16496. if (this._boundTexturesCache[channel] != null) {
  16497. this._activeChannel = channel;
  16498. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16499. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16500. if (this.webGLVersion > 1) {
  16501. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16502. }
  16503. }
  16504. return false;
  16505. }
  16506. // Video
  16507. if (texture.video) {
  16508. this._activeChannel = channel;
  16509. texture.update();
  16510. }
  16511. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16512. texture.delayLoad();
  16513. return false;
  16514. }
  16515. var internalTexture;
  16516. if (depthStencilTexture) {
  16517. internalTexture = texture.depthStencilTexture;
  16518. }
  16519. else if (texture.isReady()) {
  16520. internalTexture = texture.getInternalTexture();
  16521. }
  16522. else if (texture.isCube) {
  16523. internalTexture = this.emptyCubeTexture;
  16524. }
  16525. else if (texture.is3D) {
  16526. internalTexture = this.emptyTexture3D;
  16527. }
  16528. else {
  16529. internalTexture = this.emptyTexture;
  16530. }
  16531. if (!isPartOfTextureArray) {
  16532. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16533. }
  16534. var needToBind = true;
  16535. if (this._boundTexturesCache[channel] === internalTexture) {
  16536. this._moveBoundTextureOnTop(internalTexture);
  16537. if (!isPartOfTextureArray) {
  16538. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16539. }
  16540. needToBind = false;
  16541. }
  16542. this._activeChannel = channel;
  16543. if (internalTexture && internalTexture.is3D) {
  16544. if (needToBind) {
  16545. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16546. }
  16547. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16548. internalTexture._cachedWrapU = texture.wrapU;
  16549. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16550. }
  16551. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16552. internalTexture._cachedWrapV = texture.wrapV;
  16553. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16554. }
  16555. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16556. internalTexture._cachedWrapR = texture.wrapR;
  16557. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16558. }
  16559. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16560. }
  16561. else if (internalTexture && internalTexture.isCube) {
  16562. if (needToBind) {
  16563. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16564. }
  16565. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16566. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16567. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16568. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16569. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16570. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16571. }
  16572. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16573. }
  16574. else {
  16575. if (needToBind) {
  16576. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16577. }
  16578. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16579. internalTexture._cachedWrapU = texture.wrapU;
  16580. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16581. }
  16582. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16583. internalTexture._cachedWrapV = texture.wrapV;
  16584. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16585. }
  16586. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16587. }
  16588. return true;
  16589. };
  16590. /**
  16591. * Sets an array of texture to the webGL context
  16592. * @param channel defines the channel where the texture array must be set
  16593. * @param uniform defines the associated uniform location
  16594. * @param textures defines the array of textures to bind
  16595. */
  16596. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16597. if (channel < 0 || !uniform) {
  16598. return;
  16599. }
  16600. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16601. this._textureUnits = new Int32Array(textures.length);
  16602. }
  16603. for (var i = 0; i < textures.length; i++) {
  16604. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16605. }
  16606. this._gl.uniform1iv(uniform, this._textureUnits);
  16607. for (var index = 0; index < textures.length; index++) {
  16608. this._setTexture(this._textureUnits[index], textures[index], true);
  16609. }
  16610. };
  16611. /** @hidden */
  16612. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16613. var internalTexture = texture.getInternalTexture();
  16614. if (!internalTexture) {
  16615. return;
  16616. }
  16617. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16618. var value = texture.anisotropicFilteringLevel;
  16619. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16620. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16621. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16622. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16623. }
  16624. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16625. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16626. internalTexture._cachedAnisotropicFilteringLevel = value;
  16627. }
  16628. };
  16629. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16630. this._bindTextureDirectly(target, texture, true, true);
  16631. this._gl.texParameterf(target, parameter, value);
  16632. };
  16633. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16634. if (texture) {
  16635. this._bindTextureDirectly(target, texture, true, true);
  16636. }
  16637. this._gl.texParameteri(target, parameter, value);
  16638. };
  16639. /**
  16640. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16641. * @param x defines the x coordinate of the rectangle where pixels must be read
  16642. * @param y defines the y coordinate of the rectangle where pixels must be read
  16643. * @param width defines the width of the rectangle where pixels must be read
  16644. * @param height defines the height of the rectangle where pixels must be read
  16645. * @returns a Uint8Array containing RGBA colors
  16646. */
  16647. Engine.prototype.readPixels = function (x, y, width, height) {
  16648. var data = new Uint8Array(height * width * 4);
  16649. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16650. return data;
  16651. };
  16652. /**
  16653. * Add an externaly attached data from its key.
  16654. * This method call will fail and return false, if such key already exists.
  16655. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16656. * @param key the unique key that identifies the data
  16657. * @param data the data object to associate to the key for this Engine instance
  16658. * @return true if no such key were already present and the data was added successfully, false otherwise
  16659. */
  16660. Engine.prototype.addExternalData = function (key, data) {
  16661. if (!this._externalData) {
  16662. this._externalData = new BABYLON.StringDictionary();
  16663. }
  16664. return this._externalData.add(key, data);
  16665. };
  16666. /**
  16667. * Get an externaly attached data from its key
  16668. * @param key the unique key that identifies the data
  16669. * @return the associated data, if present (can be null), or undefined if not present
  16670. */
  16671. Engine.prototype.getExternalData = function (key) {
  16672. if (!this._externalData) {
  16673. this._externalData = new BABYLON.StringDictionary();
  16674. }
  16675. return this._externalData.get(key);
  16676. };
  16677. /**
  16678. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16679. * @param key the unique key that identifies the data
  16680. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16681. * @return the associated data, can be null if the factory returned null.
  16682. */
  16683. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16684. if (!this._externalData) {
  16685. this._externalData = new BABYLON.StringDictionary();
  16686. }
  16687. return this._externalData.getOrAddWithFactory(key, factory);
  16688. };
  16689. /**
  16690. * Remove an externaly attached data from the Engine instance
  16691. * @param key the unique key that identifies the data
  16692. * @return true if the data was successfully removed, false if it doesn't exist
  16693. */
  16694. Engine.prototype.removeExternalData = function (key) {
  16695. if (!this._externalData) {
  16696. this._externalData = new BABYLON.StringDictionary();
  16697. }
  16698. return this._externalData.remove(key);
  16699. };
  16700. /**
  16701. * Unbind all vertex attributes from the webGL context
  16702. */
  16703. Engine.prototype.unbindAllAttributes = function () {
  16704. if (this._mustWipeVertexAttributes) {
  16705. this._mustWipeVertexAttributes = false;
  16706. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16707. this._gl.disableVertexAttribArray(i);
  16708. this._vertexAttribArraysEnabled[i] = false;
  16709. this._currentBufferPointers[i].active = false;
  16710. }
  16711. return;
  16712. }
  16713. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16714. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16715. continue;
  16716. }
  16717. this._gl.disableVertexAttribArray(i);
  16718. this._vertexAttribArraysEnabled[i] = false;
  16719. this._currentBufferPointers[i].active = false;
  16720. }
  16721. };
  16722. /**
  16723. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16724. */
  16725. Engine.prototype.releaseEffects = function () {
  16726. for (var name in this._compiledEffects) {
  16727. this._deleteProgram(this._compiledEffects[name]._program);
  16728. }
  16729. this._compiledEffects = {};
  16730. };
  16731. /**
  16732. * Dispose and release all associated resources
  16733. */
  16734. Engine.prototype.dispose = function () {
  16735. this.hideLoadingUI();
  16736. this.stopRenderLoop();
  16737. // Release postProcesses
  16738. while (this.postProcesses.length) {
  16739. this.postProcesses[0].dispose();
  16740. }
  16741. // Empty texture
  16742. if (this._emptyTexture) {
  16743. this._releaseTexture(this._emptyTexture);
  16744. this._emptyTexture = null;
  16745. }
  16746. if (this._emptyCubeTexture) {
  16747. this._releaseTexture(this._emptyCubeTexture);
  16748. this._emptyCubeTexture = null;
  16749. }
  16750. // Rescale PP
  16751. if (this._rescalePostProcess) {
  16752. this._rescalePostProcess.dispose();
  16753. }
  16754. // Release scenes
  16755. while (this.scenes.length) {
  16756. this.scenes[0].dispose();
  16757. }
  16758. // Release audio engine
  16759. if (Engine.audioEngine) {
  16760. Engine.audioEngine.dispose();
  16761. }
  16762. // Release effects
  16763. this.releaseEffects();
  16764. // Unbind
  16765. this.unbindAllAttributes();
  16766. this._boundUniforms = [];
  16767. if (this._dummyFramebuffer) {
  16768. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16769. }
  16770. //WebVR
  16771. this.disableVR();
  16772. // Events
  16773. if (BABYLON.Tools.IsWindowObjectExist()) {
  16774. window.removeEventListener("blur", this._onBlur);
  16775. window.removeEventListener("focus", this._onFocus);
  16776. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16777. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16778. if (this._renderingCanvas) {
  16779. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16780. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16781. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16782. if (!this._doNotHandleContextLost) {
  16783. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16784. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16785. }
  16786. }
  16787. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16788. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16789. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16790. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16791. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16792. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16793. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16794. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16795. if (this._onVrDisplayConnect) {
  16796. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16797. if (this._onVrDisplayDisconnect) {
  16798. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16799. }
  16800. if (this._onVrDisplayPresentChange) {
  16801. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16802. }
  16803. this._onVrDisplayConnect = null;
  16804. this._onVrDisplayDisconnect = null;
  16805. }
  16806. }
  16807. // Remove from Instances
  16808. var index = Engine.Instances.indexOf(this);
  16809. if (index >= 0) {
  16810. Engine.Instances.splice(index, 1);
  16811. }
  16812. this._workingCanvas = null;
  16813. this._workingContext = null;
  16814. this._currentBufferPointers = [];
  16815. this._renderingCanvas = null;
  16816. this._currentProgram = null;
  16817. this._bindedRenderFunction = null;
  16818. this.onResizeObservable.clear();
  16819. this.onCanvasBlurObservable.clear();
  16820. this.onCanvasFocusObservable.clear();
  16821. this.onCanvasPointerOutObservable.clear();
  16822. this.onBeginFrameObservable.clear();
  16823. this.onEndFrameObservable.clear();
  16824. BABYLON.Effect.ResetCache();
  16825. // Abort active requests
  16826. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16827. var request = _a[_i];
  16828. request.abort();
  16829. }
  16830. };
  16831. // Loading screen
  16832. /**
  16833. * Display the loading screen
  16834. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16835. */
  16836. Engine.prototype.displayLoadingUI = function () {
  16837. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16838. return;
  16839. }
  16840. var loadingScreen = this.loadingScreen;
  16841. if (loadingScreen) {
  16842. loadingScreen.displayLoadingUI();
  16843. }
  16844. };
  16845. /**
  16846. * Hide the loading screen
  16847. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16848. */
  16849. Engine.prototype.hideLoadingUI = function () {
  16850. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16851. return;
  16852. }
  16853. var loadingScreen = this.loadingScreen;
  16854. if (loadingScreen) {
  16855. loadingScreen.hideLoadingUI();
  16856. }
  16857. };
  16858. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16859. /**
  16860. * Gets the current loading screen object
  16861. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16862. */
  16863. get: function () {
  16864. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16865. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16866. return this._loadingScreen;
  16867. },
  16868. /**
  16869. * Sets the current loading screen object
  16870. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16871. */
  16872. set: function (loadingScreen) {
  16873. this._loadingScreen = loadingScreen;
  16874. },
  16875. enumerable: true,
  16876. configurable: true
  16877. });
  16878. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16879. /**
  16880. * Sets the current loading screen text
  16881. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16882. */
  16883. set: function (text) {
  16884. this.loadingScreen.loadingUIText = text;
  16885. },
  16886. enumerable: true,
  16887. configurable: true
  16888. });
  16889. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16890. /**
  16891. * Sets the current loading screen background color
  16892. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16893. */
  16894. set: function (color) {
  16895. this.loadingScreen.loadingUIBackgroundColor = color;
  16896. },
  16897. enumerable: true,
  16898. configurable: true
  16899. });
  16900. /**
  16901. * Attach a new callback raised when context lost event is fired
  16902. * @param callback defines the callback to call
  16903. */
  16904. Engine.prototype.attachContextLostEvent = function (callback) {
  16905. if (this._renderingCanvas) {
  16906. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16907. }
  16908. };
  16909. /**
  16910. * Attach a new callback raised when context restored event is fired
  16911. * @param callback defines the callback to call
  16912. */
  16913. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16914. if (this._renderingCanvas) {
  16915. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16916. }
  16917. };
  16918. /**
  16919. * Gets the source code of the vertex shader associated with a specific webGL program
  16920. * @param program defines the program to use
  16921. * @returns a string containing the source code of the vertex shader associated with the program
  16922. */
  16923. Engine.prototype.getVertexShaderSource = function (program) {
  16924. var shaders = this._gl.getAttachedShaders(program);
  16925. if (!shaders) {
  16926. return null;
  16927. }
  16928. return this._gl.getShaderSource(shaders[0]);
  16929. };
  16930. /**
  16931. * Gets the source code of the fragment shader associated with a specific webGL program
  16932. * @param program defines the program to use
  16933. * @returns a string containing the source code of the fragment shader associated with the program
  16934. */
  16935. Engine.prototype.getFragmentShaderSource = function (program) {
  16936. var shaders = this._gl.getAttachedShaders(program);
  16937. if (!shaders) {
  16938. return null;
  16939. }
  16940. return this._gl.getShaderSource(shaders[1]);
  16941. };
  16942. /**
  16943. * Get the current error code of the webGL context
  16944. * @returns the error code
  16945. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16946. */
  16947. Engine.prototype.getError = function () {
  16948. return this._gl.getError();
  16949. };
  16950. // FPS
  16951. /**
  16952. * Gets the current framerate
  16953. * @returns a number representing the framerate
  16954. */
  16955. Engine.prototype.getFps = function () {
  16956. return this._fps;
  16957. };
  16958. /**
  16959. * Gets the time spent between current and previous frame
  16960. * @returns a number representing the delta time in ms
  16961. */
  16962. Engine.prototype.getDeltaTime = function () {
  16963. return this._deltaTime;
  16964. };
  16965. Engine.prototype._measureFps = function () {
  16966. this._performanceMonitor.sampleFrame();
  16967. this._fps = this._performanceMonitor.averageFPS;
  16968. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16969. };
  16970. /** @hidden */
  16971. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16972. if (faceIndex === void 0) { faceIndex = -1; }
  16973. if (level === void 0) { level = 0; }
  16974. var gl = this._gl;
  16975. if (!this._dummyFramebuffer) {
  16976. var dummy = gl.createFramebuffer();
  16977. if (!dummy) {
  16978. throw new Error("Unable to create dummy framebuffer");
  16979. }
  16980. this._dummyFramebuffer = dummy;
  16981. }
  16982. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16983. if (faceIndex > -1) {
  16984. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16985. }
  16986. else {
  16987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16988. }
  16989. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16990. var buffer;
  16991. switch (readType) {
  16992. case gl.UNSIGNED_BYTE:
  16993. buffer = new Uint8Array(4 * width * height);
  16994. readType = gl.UNSIGNED_BYTE;
  16995. break;
  16996. default:
  16997. buffer = new Float32Array(4 * width * height);
  16998. readType = gl.FLOAT;
  16999. break;
  17000. }
  17001. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17002. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17003. return buffer;
  17004. };
  17005. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17006. if (this._webGLVersion > 1) {
  17007. return this._caps.colorBufferFloat;
  17008. }
  17009. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17010. };
  17011. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17012. if (this._webGLVersion > 1) {
  17013. return this._caps.colorBufferFloat;
  17014. }
  17015. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17016. };
  17017. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17018. Engine.prototype._canRenderToFramebuffer = function (type) {
  17019. var gl = this._gl;
  17020. //clear existing errors
  17021. while (gl.getError() !== gl.NO_ERROR) { }
  17022. var successful = true;
  17023. var texture = gl.createTexture();
  17024. gl.bindTexture(gl.TEXTURE_2D, texture);
  17025. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17026. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17027. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17028. var fb = gl.createFramebuffer();
  17029. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17031. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17032. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17033. successful = successful && (gl.getError() === gl.NO_ERROR);
  17034. //try render by clearing frame buffer's color buffer
  17035. if (successful) {
  17036. gl.clear(gl.COLOR_BUFFER_BIT);
  17037. successful = successful && (gl.getError() === gl.NO_ERROR);
  17038. }
  17039. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17040. if (successful) {
  17041. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17042. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17043. var readFormat = gl.RGBA;
  17044. var readType = gl.UNSIGNED_BYTE;
  17045. var buffer = new Uint8Array(4);
  17046. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17047. successful = successful && (gl.getError() === gl.NO_ERROR);
  17048. }
  17049. //clean up
  17050. gl.deleteTexture(texture);
  17051. gl.deleteFramebuffer(fb);
  17052. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17053. //clear accumulated errors
  17054. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17055. return successful;
  17056. };
  17057. /** @hidden */
  17058. Engine.prototype._getWebGLTextureType = function (type) {
  17059. if (type === Engine.TEXTURETYPE_FLOAT) {
  17060. return this._gl.FLOAT;
  17061. }
  17062. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17063. // Add Half Float Constant.
  17064. return this._gl.HALF_FLOAT_OES;
  17065. }
  17066. return this._gl.UNSIGNED_BYTE;
  17067. };
  17068. ;
  17069. Engine.prototype._getInternalFormat = function (format) {
  17070. var internalFormat = this._gl.RGBA;
  17071. switch (format) {
  17072. case Engine.TEXTUREFORMAT_ALPHA:
  17073. internalFormat = this._gl.ALPHA;
  17074. break;
  17075. case Engine.TEXTUREFORMAT_LUMINANCE:
  17076. internalFormat = this._gl.LUMINANCE;
  17077. break;
  17078. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17079. internalFormat = this._gl.LUMINANCE_ALPHA;
  17080. break;
  17081. case Engine.TEXTUREFORMAT_RGB:
  17082. internalFormat = this._gl.RGB;
  17083. break;
  17084. case Engine.TEXTUREFORMAT_RGBA:
  17085. internalFormat = this._gl.RGBA;
  17086. break;
  17087. case Engine.TEXTUREFORMAT_R:
  17088. internalFormat = this._gl.RED;
  17089. break;
  17090. case Engine.TEXTUREFORMAT_RG:
  17091. internalFormat = this._gl.RG;
  17092. break;
  17093. }
  17094. return internalFormat;
  17095. };
  17096. /** @hidden */
  17097. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17098. if (this._webGLVersion === 1) {
  17099. if (format !== undefined) {
  17100. switch (format) {
  17101. case Engine.TEXTUREFORMAT_LUMINANCE:
  17102. return this._gl.LUMINANCE;
  17103. case Engine.TEXTUREFORMAT_ALPHA:
  17104. return this._gl.ALPHA;
  17105. }
  17106. }
  17107. return this._gl.RGBA;
  17108. }
  17109. if (type === Engine.TEXTURETYPE_FLOAT) {
  17110. if (format !== undefined) {
  17111. switch (format) {
  17112. case Engine.TEXTUREFORMAT_R:
  17113. return this._gl.R32F;
  17114. case Engine.TEXTUREFORMAT_RG:
  17115. return this._gl.RG32F;
  17116. case Engine.TEXTUREFORMAT_RGB:
  17117. return this._gl.RGB32F;
  17118. }
  17119. }
  17120. return this._gl.RGBA32F;
  17121. }
  17122. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17123. if (format) {
  17124. switch (format) {
  17125. case Engine.TEXTUREFORMAT_R:
  17126. return this._gl.R16F;
  17127. case Engine.TEXTUREFORMAT_RG:
  17128. return this._gl.RG16F;
  17129. case Engine.TEXTUREFORMAT_RGB:
  17130. return this._gl.RGB16F;
  17131. }
  17132. }
  17133. return this._gl.RGBA16F;
  17134. }
  17135. if (format !== undefined) {
  17136. switch (format) {
  17137. case Engine.TEXTUREFORMAT_LUMINANCE:
  17138. return this._gl.LUMINANCE;
  17139. case Engine.TEXTUREFORMAT_RGB:
  17140. return this._gl.RGB;
  17141. case Engine.TEXTUREFORMAT_R:
  17142. return this._gl.R8;
  17143. case Engine.TEXTUREFORMAT_RG:
  17144. return this._gl.RG8;
  17145. case Engine.TEXTUREFORMAT_ALPHA:
  17146. return this._gl.ALPHA;
  17147. }
  17148. }
  17149. return this._gl.RGBA;
  17150. };
  17151. ;
  17152. /** @hidden */
  17153. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17154. if (type === Engine.TEXTURETYPE_FLOAT) {
  17155. return this._gl.RGBA32F;
  17156. }
  17157. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17158. return this._gl.RGBA16F;
  17159. }
  17160. return this._gl.RGBA8;
  17161. };
  17162. ;
  17163. /**
  17164. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17165. * @return the new query
  17166. */
  17167. Engine.prototype.createQuery = function () {
  17168. return this._gl.createQuery();
  17169. };
  17170. /**
  17171. * Delete and release a webGL query
  17172. * @param query defines the query to delete
  17173. * @return the current engine
  17174. */
  17175. Engine.prototype.deleteQuery = function (query) {
  17176. this._gl.deleteQuery(query);
  17177. return this;
  17178. };
  17179. /**
  17180. * Check if a given query has resolved and got its value
  17181. * @param query defines the query to check
  17182. * @returns true if the query got its value
  17183. */
  17184. Engine.prototype.isQueryResultAvailable = function (query) {
  17185. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17186. };
  17187. /**
  17188. * Gets the value of a given query
  17189. * @param query defines the query to check
  17190. * @returns the value of the query
  17191. */
  17192. Engine.prototype.getQueryResult = function (query) {
  17193. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17194. };
  17195. /**
  17196. * Initiates an occlusion query
  17197. * @param algorithmType defines the algorithm to use
  17198. * @param query defines the query to use
  17199. * @returns the current engine
  17200. * @see http://doc.babylonjs.com/features/occlusionquery
  17201. */
  17202. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17203. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17204. this._gl.beginQuery(glAlgorithm, query);
  17205. return this;
  17206. };
  17207. /**
  17208. * Ends an occlusion query
  17209. * @see http://doc.babylonjs.com/features/occlusionquery
  17210. * @param algorithmType defines the algorithm to use
  17211. * @returns the current engine
  17212. */
  17213. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17214. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17215. this._gl.endQuery(glAlgorithm);
  17216. return this;
  17217. };
  17218. /* Time queries */
  17219. Engine.prototype._createTimeQuery = function () {
  17220. var timerQuery = this._caps.timerQuery;
  17221. if (timerQuery.createQueryEXT) {
  17222. return timerQuery.createQueryEXT();
  17223. }
  17224. return this.createQuery();
  17225. };
  17226. Engine.prototype._deleteTimeQuery = function (query) {
  17227. var timerQuery = this._caps.timerQuery;
  17228. if (timerQuery.deleteQueryEXT) {
  17229. timerQuery.deleteQueryEXT(query);
  17230. return;
  17231. }
  17232. this.deleteQuery(query);
  17233. };
  17234. Engine.prototype._getTimeQueryResult = function (query) {
  17235. var timerQuery = this._caps.timerQuery;
  17236. if (timerQuery.getQueryObjectEXT) {
  17237. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17238. }
  17239. return this.getQueryResult(query);
  17240. };
  17241. Engine.prototype._getTimeQueryAvailability = function (query) {
  17242. var timerQuery = this._caps.timerQuery;
  17243. if (timerQuery.getQueryObjectEXT) {
  17244. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17245. }
  17246. return this.isQueryResultAvailable(query);
  17247. };
  17248. /**
  17249. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17250. * Please note that only one query can be issued at a time
  17251. * @returns a time token used to track the time span
  17252. */
  17253. Engine.prototype.startTimeQuery = function () {
  17254. var timerQuery = this._caps.timerQuery;
  17255. if (!timerQuery) {
  17256. return null;
  17257. }
  17258. var token = new BABYLON._TimeToken();
  17259. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17260. if (this._caps.canUseTimestampForTimerQuery) {
  17261. token._startTimeQuery = this._createTimeQuery();
  17262. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17263. }
  17264. else {
  17265. if (this._currentNonTimestampToken) {
  17266. return this._currentNonTimestampToken;
  17267. }
  17268. token._timeElapsedQuery = this._createTimeQuery();
  17269. if (timerQuery.beginQueryEXT) {
  17270. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17271. }
  17272. else {
  17273. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17274. }
  17275. this._currentNonTimestampToken = token;
  17276. }
  17277. return token;
  17278. };
  17279. /**
  17280. * Ends a time query
  17281. * @param token defines the token used to measure the time span
  17282. * @returns the time spent (in ns)
  17283. */
  17284. Engine.prototype.endTimeQuery = function (token) {
  17285. var timerQuery = this._caps.timerQuery;
  17286. if (!timerQuery || !token) {
  17287. return -1;
  17288. }
  17289. if (this._caps.canUseTimestampForTimerQuery) {
  17290. if (!token._startTimeQuery) {
  17291. return -1;
  17292. }
  17293. if (!token._endTimeQuery) {
  17294. token._endTimeQuery = this._createTimeQuery();
  17295. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17296. }
  17297. }
  17298. else if (!token._timeElapsedQueryEnded) {
  17299. if (!token._timeElapsedQuery) {
  17300. return -1;
  17301. }
  17302. if (timerQuery.endQueryEXT) {
  17303. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17304. }
  17305. else {
  17306. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17307. }
  17308. token._timeElapsedQueryEnded = true;
  17309. }
  17310. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17311. var available = false;
  17312. if (token._endTimeQuery) {
  17313. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17314. }
  17315. else if (token._timeElapsedQuery) {
  17316. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17317. }
  17318. if (available && !disjoint) {
  17319. var result = 0;
  17320. if (this._caps.canUseTimestampForTimerQuery) {
  17321. if (!token._startTimeQuery || !token._endTimeQuery) {
  17322. return -1;
  17323. }
  17324. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17325. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17326. result = timeEnd - timeStart;
  17327. this._deleteTimeQuery(token._startTimeQuery);
  17328. this._deleteTimeQuery(token._endTimeQuery);
  17329. token._startTimeQuery = null;
  17330. token._endTimeQuery = null;
  17331. }
  17332. else {
  17333. if (!token._timeElapsedQuery) {
  17334. return -1;
  17335. }
  17336. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17337. this._deleteTimeQuery(token._timeElapsedQuery);
  17338. token._timeElapsedQuery = null;
  17339. token._timeElapsedQueryEnded = false;
  17340. this._currentNonTimestampToken = null;
  17341. }
  17342. return result;
  17343. }
  17344. return -1;
  17345. };
  17346. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17347. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17348. };
  17349. // Transform feedback
  17350. /**
  17351. * Creates a webGL transform feedback object
  17352. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17353. * @returns the webGL transform feedback object
  17354. */
  17355. Engine.prototype.createTransformFeedback = function () {
  17356. return this._gl.createTransformFeedback();
  17357. };
  17358. /**
  17359. * Delete a webGL transform feedback object
  17360. * @param value defines the webGL transform feedback object to delete
  17361. */
  17362. Engine.prototype.deleteTransformFeedback = function (value) {
  17363. this._gl.deleteTransformFeedback(value);
  17364. };
  17365. /**
  17366. * Bind a webGL transform feedback object to the webgl context
  17367. * @param value defines the webGL transform feedback object to bind
  17368. */
  17369. Engine.prototype.bindTransformFeedback = function (value) {
  17370. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17371. };
  17372. /**
  17373. * Begins a transform feedback operation
  17374. * @param usePoints defines if points or triangles must be used
  17375. */
  17376. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17377. if (usePoints === void 0) { usePoints = true; }
  17378. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17379. };
  17380. /**
  17381. * Ends a transform feedback operation
  17382. */
  17383. Engine.prototype.endTransformFeedback = function () {
  17384. this._gl.endTransformFeedback();
  17385. };
  17386. /**
  17387. * Specify the varyings to use with transform feedback
  17388. * @param program defines the associated webGL program
  17389. * @param value defines the list of strings representing the varying names
  17390. */
  17391. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17392. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17393. };
  17394. /**
  17395. * Bind a webGL buffer for a transform feedback operation
  17396. * @param value defines the webGL buffer to bind
  17397. */
  17398. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17399. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17400. };
  17401. /** @hidden */
  17402. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17403. var _this = this;
  17404. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17405. this._activeRequests.push(request);
  17406. request.onCompleteObservable.add(function (request) {
  17407. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17408. });
  17409. return request;
  17410. };
  17411. /** @hidden */
  17412. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17413. var _this = this;
  17414. return new Promise(function (resolve, reject) {
  17415. _this._loadFile(url, function (data) {
  17416. resolve(data);
  17417. }, undefined, database, useArrayBuffer, function (request, exception) {
  17418. reject(exception);
  17419. });
  17420. });
  17421. };
  17422. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17423. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17424. var onload = function (data) {
  17425. loadedFiles[index] = data;
  17426. loadedFiles._internalCount++;
  17427. if (loadedFiles._internalCount === 6) {
  17428. onfinish(loadedFiles);
  17429. }
  17430. };
  17431. var onerror = function (request, exception) {
  17432. if (onErrorCallBack && request) {
  17433. onErrorCallBack(request.status + " " + request.statusText, exception);
  17434. }
  17435. };
  17436. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17437. };
  17438. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17439. if (onError === void 0) { onError = null; }
  17440. var loadedFiles = [];
  17441. loadedFiles._internalCount = 0;
  17442. for (var index = 0; index < 6; index++) {
  17443. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17444. }
  17445. };
  17446. // Statics
  17447. /**
  17448. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17449. * @returns true if the engine can be created
  17450. * @ignorenaming
  17451. */
  17452. Engine.isSupported = function () {
  17453. try {
  17454. var tempcanvas = document.createElement("canvas");
  17455. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17456. return gl != null && !!window.WebGLRenderingContext;
  17457. }
  17458. catch (e) {
  17459. return false;
  17460. }
  17461. };
  17462. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17463. Engine.ExceptionList = [
  17464. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17465. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17466. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17467. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17468. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17469. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17470. ];
  17471. /** Gets the list of created engines */
  17472. Engine.Instances = new Array();
  17473. // Const statics
  17474. Engine._ALPHA_DISABLE = 0;
  17475. Engine._ALPHA_ADD = 1;
  17476. Engine._ALPHA_COMBINE = 2;
  17477. Engine._ALPHA_SUBTRACT = 3;
  17478. Engine._ALPHA_MULTIPLY = 4;
  17479. Engine._ALPHA_MAXIMIZED = 5;
  17480. Engine._ALPHA_ONEONE = 6;
  17481. Engine._ALPHA_PREMULTIPLIED = 7;
  17482. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17483. Engine._ALPHA_INTERPOLATE = 9;
  17484. Engine._ALPHA_SCREENMODE = 10;
  17485. Engine._DELAYLOADSTATE_NONE = 0;
  17486. Engine._DELAYLOADSTATE_LOADED = 1;
  17487. Engine._DELAYLOADSTATE_LOADING = 2;
  17488. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17489. Engine._TEXTUREFORMAT_ALPHA = 0;
  17490. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17491. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17492. Engine._TEXTUREFORMAT_RGB = 4;
  17493. Engine._TEXTUREFORMAT_RGBA = 5;
  17494. Engine._TEXTUREFORMAT_R = 6;
  17495. Engine._TEXTUREFORMAT_RG = 7;
  17496. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17497. Engine._TEXTURETYPE_FLOAT = 1;
  17498. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17499. // Depht or Stencil test Constants.
  17500. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17501. 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.
  17502. 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.
  17503. 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.
  17504. 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.
  17505. 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.
  17506. 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.
  17507. 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.
  17508. // Stencil Actions Constants.
  17509. Engine._KEEP = 0x1E00;
  17510. Engine._REPLACE = 0x1E01;
  17511. Engine._INCR = 0x1E02;
  17512. Engine._DECR = 0x1E03;
  17513. Engine._INVERT = 0x150A;
  17514. Engine._INCR_WRAP = 0x8507;
  17515. Engine._DECR_WRAP = 0x8508;
  17516. // Texture rescaling mode
  17517. Engine._SCALEMODE_FLOOR = 1;
  17518. Engine._SCALEMODE_NEAREST = 2;
  17519. Engine._SCALEMODE_CEILING = 3;
  17520. // Updatable statics so stick with vars here
  17521. /**
  17522. * Gets or sets the epsilon value used by collision engine
  17523. */
  17524. Engine.CollisionsEpsilon = 0.001;
  17525. /**
  17526. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17527. */
  17528. Engine.CodeRepository = "src/";
  17529. /**
  17530. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17531. */
  17532. Engine.ShadersRepository = "src/Shaders/";
  17533. return Engine;
  17534. }());
  17535. BABYLON.Engine = Engine;
  17536. })(BABYLON || (BABYLON = {}));
  17537. //# sourceMappingURL=babylon.engine.js.map
  17538. var BABYLON;
  17539. (function (BABYLON) {
  17540. /**
  17541. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17542. */
  17543. var Node = /** @class */ (function () {
  17544. /**
  17545. * Creates a new Node
  17546. * @param {string} name - the name and id to be given to this node
  17547. * @param {BABYLON.Scene} the scene this node will be added to
  17548. */
  17549. function Node(name, scene) {
  17550. if (scene === void 0) { scene = null; }
  17551. /**
  17552. * Gets or sets a string used to store user defined state for the node
  17553. */
  17554. this.state = "";
  17555. /**
  17556. * Gets or sets an object used to store user defined information for the node
  17557. */
  17558. this.metadata = null;
  17559. /**
  17560. * Gets or sets a boolean used to define if the node must be serialized
  17561. */
  17562. this.doNotSerialize = false;
  17563. /** @hidden */
  17564. this._isDisposed = false;
  17565. /**
  17566. * Gets a list of Animations associated with the node
  17567. */
  17568. this.animations = new Array();
  17569. this._ranges = {};
  17570. this._isEnabled = true;
  17571. this._isReady = true;
  17572. /** @hidden */
  17573. this._currentRenderId = -1;
  17574. this._parentRenderId = -1;
  17575. this._childRenderId = -1;
  17576. this._animationPropertiesOverride = null;
  17577. /**
  17578. * An event triggered when the mesh is disposed
  17579. */
  17580. this.onDisposeObservable = new BABYLON.Observable();
  17581. // Behaviors
  17582. this._behaviors = new Array();
  17583. this.name = name;
  17584. this.id = name;
  17585. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17586. this.uniqueId = this._scene.getUniqueId();
  17587. this._initCache();
  17588. }
  17589. /**
  17590. * Gets a boolean indicating if the node has been disposed
  17591. * @returns true if the node was disposed
  17592. */
  17593. Node.prototype.isDisposed = function () {
  17594. return this._isDisposed;
  17595. };
  17596. Object.defineProperty(Node.prototype, "parent", {
  17597. get: function () {
  17598. return this._parentNode;
  17599. },
  17600. /**
  17601. * Gets or sets the parent of the node
  17602. */
  17603. set: function (parent) {
  17604. if (this._parentNode === parent) {
  17605. return;
  17606. }
  17607. // Remove self from list of children of parent
  17608. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17609. var index = this._parentNode._children.indexOf(this);
  17610. if (index !== -1) {
  17611. this._parentNode._children.splice(index, 1);
  17612. }
  17613. }
  17614. // Store new parent
  17615. this._parentNode = parent;
  17616. // Add as child to new parent
  17617. if (this._parentNode) {
  17618. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17619. this._parentNode._children = new Array();
  17620. }
  17621. this._parentNode._children.push(this);
  17622. }
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17628. /**
  17629. * Gets or sets the animation properties override
  17630. */
  17631. get: function () {
  17632. if (!this._animationPropertiesOverride) {
  17633. return this._scene.animationPropertiesOverride;
  17634. }
  17635. return this._animationPropertiesOverride;
  17636. },
  17637. set: function (value) {
  17638. this._animationPropertiesOverride = value;
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. /**
  17644. * Gets a string idenfifying the name of the class
  17645. * @returns "Node" string
  17646. */
  17647. Node.prototype.getClassName = function () {
  17648. return "Node";
  17649. };
  17650. Object.defineProperty(Node.prototype, "onDispose", {
  17651. /**
  17652. * Sets a callback that will be raised when the node will be disposed
  17653. */
  17654. set: function (callback) {
  17655. if (this._onDisposeObserver) {
  17656. this.onDisposeObservable.remove(this._onDisposeObserver);
  17657. }
  17658. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17659. },
  17660. enumerable: true,
  17661. configurable: true
  17662. });
  17663. /**
  17664. * Gets the scene of the node
  17665. * @returns a {BABYLON.Scene}
  17666. */
  17667. Node.prototype.getScene = function () {
  17668. return this._scene;
  17669. };
  17670. /**
  17671. * Gets the engine of the node
  17672. * @returns a {BABYLON.Engine}
  17673. */
  17674. Node.prototype.getEngine = function () {
  17675. return this._scene.getEngine();
  17676. };
  17677. /**
  17678. * Attach a behavior to the node
  17679. * @see http://doc.babylonjs.com/features/behaviour
  17680. * @param behavior defines the behavior to attach
  17681. * @returns the current Node
  17682. */
  17683. Node.prototype.addBehavior = function (behavior) {
  17684. var _this = this;
  17685. var index = this._behaviors.indexOf(behavior);
  17686. if (index !== -1) {
  17687. return this;
  17688. }
  17689. behavior.init();
  17690. if (this._scene.isLoading) {
  17691. // We defer the attach when the scene will be loaded
  17692. this._scene.onDataLoadedObservable.addOnce(function () {
  17693. behavior.attach(_this);
  17694. });
  17695. }
  17696. else {
  17697. behavior.attach(this);
  17698. }
  17699. this._behaviors.push(behavior);
  17700. return this;
  17701. };
  17702. /**
  17703. * Remove an attached behavior
  17704. * @see http://doc.babylonjs.com/features/behaviour
  17705. * @param behavior defines the behavior to attach
  17706. * @returns the current Node
  17707. */
  17708. Node.prototype.removeBehavior = function (behavior) {
  17709. var index = this._behaviors.indexOf(behavior);
  17710. if (index === -1) {
  17711. return this;
  17712. }
  17713. this._behaviors[index].detach();
  17714. this._behaviors.splice(index, 1);
  17715. return this;
  17716. };
  17717. Object.defineProperty(Node.prototype, "behaviors", {
  17718. /**
  17719. * Gets the list of attached behaviors
  17720. * @see http://doc.babylonjs.com/features/behaviour
  17721. */
  17722. get: function () {
  17723. return this._behaviors;
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. /**
  17729. * Gets an attached behavior by name
  17730. * @param name defines the name of the behavior to look for
  17731. * @see http://doc.babylonjs.com/features/behaviour
  17732. * @returns null if behavior was not found else the requested behavior
  17733. */
  17734. Node.prototype.getBehaviorByName = function (name) {
  17735. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17736. var behavior = _a[_i];
  17737. if (behavior.name === name) {
  17738. return behavior;
  17739. }
  17740. }
  17741. return null;
  17742. };
  17743. /**
  17744. * Returns the world matrix of the node
  17745. * @returns a matrix containing the node's world matrix
  17746. */
  17747. Node.prototype.getWorldMatrix = function () {
  17748. return BABYLON.Matrix.Identity();
  17749. };
  17750. /** @hidden */
  17751. Node.prototype._getWorldMatrixDeterminant = function () {
  17752. return 1;
  17753. };
  17754. // override it in derived class if you add new variables to the cache
  17755. // and call the parent class method
  17756. /** @hidden */
  17757. Node.prototype._initCache = function () {
  17758. this._cache = {};
  17759. this._cache.parent = undefined;
  17760. };
  17761. /** @hidden */
  17762. Node.prototype.updateCache = function (force) {
  17763. if (!force && this.isSynchronized())
  17764. return;
  17765. this._cache.parent = this.parent;
  17766. this._updateCache();
  17767. };
  17768. // override it in derived class if you add new variables to the cache
  17769. // and call the parent class method if !ignoreParentClass
  17770. /** @hidden */
  17771. Node.prototype._updateCache = function (ignoreParentClass) {
  17772. };
  17773. // override it in derived class if you add new variables to the cache
  17774. /** @hidden */
  17775. Node.prototype._isSynchronized = function () {
  17776. return true;
  17777. };
  17778. /** @hidden */
  17779. Node.prototype._markSyncedWithParent = function () {
  17780. if (this.parent) {
  17781. this._parentRenderId = this.parent._childRenderId;
  17782. }
  17783. };
  17784. /** @hidden */
  17785. Node.prototype.isSynchronizedWithParent = function () {
  17786. if (!this.parent) {
  17787. return true;
  17788. }
  17789. if (this._parentRenderId !== this.parent._childRenderId) {
  17790. return false;
  17791. }
  17792. return this.parent.isSynchronized();
  17793. };
  17794. /** @hidden */
  17795. Node.prototype.isSynchronized = function (updateCache) {
  17796. var check = this.hasNewParent();
  17797. check = check || !this.isSynchronizedWithParent();
  17798. check = check || !this._isSynchronized();
  17799. if (updateCache)
  17800. this.updateCache(true);
  17801. return !check;
  17802. };
  17803. /** @hidden */
  17804. Node.prototype.hasNewParent = function (update) {
  17805. if (this._cache.parent === this.parent)
  17806. return false;
  17807. if (update)
  17808. this._cache.parent = this.parent;
  17809. return true;
  17810. };
  17811. /**
  17812. * Is this node ready to be used/rendered
  17813. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17814. * @return true if the node is ready
  17815. */
  17816. Node.prototype.isReady = function (completeCheck) {
  17817. if (completeCheck === void 0) { completeCheck = false; }
  17818. return this._isReady;
  17819. };
  17820. /**
  17821. * Is this node enabled?
  17822. * 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
  17823. * @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
  17824. * @return whether this node (and its parent) is enabled
  17825. */
  17826. Node.prototype.isEnabled = function (checkAncestors) {
  17827. if (checkAncestors === void 0) { checkAncestors = true; }
  17828. if (checkAncestors === false) {
  17829. return this._isEnabled;
  17830. }
  17831. if (this._isEnabled === false) {
  17832. return false;
  17833. }
  17834. if (this.parent !== undefined && this.parent !== null) {
  17835. return this.parent.isEnabled(checkAncestors);
  17836. }
  17837. return true;
  17838. };
  17839. /**
  17840. * Set the enabled state of this node
  17841. * @param value defines the new enabled state
  17842. */
  17843. Node.prototype.setEnabled = function (value) {
  17844. this._isEnabled = value;
  17845. };
  17846. /**
  17847. * Is this node a descendant of the given node?
  17848. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17849. * @param ancestor defines the parent node to inspect
  17850. * @returns a boolean indicating if this node is a descendant of the given node
  17851. */
  17852. Node.prototype.isDescendantOf = function (ancestor) {
  17853. if (this.parent) {
  17854. if (this.parent === ancestor) {
  17855. return true;
  17856. }
  17857. return this.parent.isDescendantOf(ancestor);
  17858. }
  17859. return false;
  17860. };
  17861. /** @hidden */
  17862. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17863. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17864. if (!this._children) {
  17865. return;
  17866. }
  17867. for (var index = 0; index < this._children.length; index++) {
  17868. var item = this._children[index];
  17869. if (!predicate || predicate(item)) {
  17870. results.push(item);
  17871. }
  17872. if (!directDescendantsOnly) {
  17873. item._getDescendants(results, false, predicate);
  17874. }
  17875. }
  17876. };
  17877. /**
  17878. * Will return all nodes that have this node as ascendant
  17879. * @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
  17880. * @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
  17881. * @return all children nodes of all types
  17882. */
  17883. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17884. var results = new Array();
  17885. this._getDescendants(results, directDescendantsOnly, predicate);
  17886. return results;
  17887. };
  17888. /**
  17889. * Get all child-meshes of this node
  17890. * @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
  17891. * @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
  17892. * @returns an array of {BABYLON.AbstractMesh}
  17893. */
  17894. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17895. var results = [];
  17896. this._getDescendants(results, directDescendantsOnly, function (node) {
  17897. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17898. });
  17899. return results;
  17900. };
  17901. /**
  17902. * Get all child-transformNodes of this node
  17903. * @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
  17904. * @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
  17905. * @returns an array of {BABYLON.TransformNode}
  17906. */
  17907. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17908. var results = [];
  17909. this._getDescendants(results, directDescendantsOnly, function (node) {
  17910. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17911. });
  17912. return results;
  17913. };
  17914. /**
  17915. * Get all direct children of this node
  17916. * @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
  17917. * @returns an array of {BABYLON.Node}
  17918. */
  17919. Node.prototype.getChildren = function (predicate) {
  17920. return this.getDescendants(true, predicate);
  17921. };
  17922. /** @hidden */
  17923. Node.prototype._setReady = function (state) {
  17924. if (state === this._isReady) {
  17925. return;
  17926. }
  17927. if (!state) {
  17928. this._isReady = false;
  17929. return;
  17930. }
  17931. if (this.onReady) {
  17932. this.onReady(this);
  17933. }
  17934. this._isReady = true;
  17935. };
  17936. /**
  17937. * Get an animation by name
  17938. * @param name defines the name of the animation to look for
  17939. * @returns null if not found else the requested animation
  17940. */
  17941. Node.prototype.getAnimationByName = function (name) {
  17942. for (var i = 0; i < this.animations.length; i++) {
  17943. var animation = this.animations[i];
  17944. if (animation.name === name) {
  17945. return animation;
  17946. }
  17947. }
  17948. return null;
  17949. };
  17950. /**
  17951. * Creates an animation range for this node
  17952. * @param name defines the name of the range
  17953. * @param from defines the starting key
  17954. * @param to defines the end key
  17955. */
  17956. Node.prototype.createAnimationRange = function (name, from, to) {
  17957. // check name not already in use
  17958. if (!this._ranges[name]) {
  17959. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17960. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17961. if (this.animations[i]) {
  17962. this.animations[i].createRange(name, from, to);
  17963. }
  17964. }
  17965. }
  17966. };
  17967. /**
  17968. * Delete a specific animation range
  17969. * @param name defines the name of the range to delete
  17970. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17971. */
  17972. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17973. if (deleteFrames === void 0) { deleteFrames = true; }
  17974. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17975. if (this.animations[i]) {
  17976. this.animations[i].deleteRange(name, deleteFrames);
  17977. }
  17978. }
  17979. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17980. };
  17981. /**
  17982. * Get an animation range by name
  17983. * @param name defines the name of the animation range to look for
  17984. * @returns null if not found else the requested animation range
  17985. */
  17986. Node.prototype.getAnimationRange = function (name) {
  17987. return this._ranges[name];
  17988. };
  17989. /**
  17990. * Will start the animation sequence
  17991. * @param name defines the range frames for animation sequence
  17992. * @param loop defines if the animation should loop (false by default)
  17993. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17994. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17995. * @returns the object created for this animation. If range does not exist, it will return null
  17996. */
  17997. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17998. var range = this.getAnimationRange(name);
  17999. if (!range) {
  18000. return null;
  18001. }
  18002. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18003. };
  18004. /**
  18005. * Serialize animation ranges into a JSON compatible object
  18006. * @returns serialization object
  18007. */
  18008. Node.prototype.serializeAnimationRanges = function () {
  18009. var serializationRanges = [];
  18010. for (var name in this._ranges) {
  18011. var localRange = this._ranges[name];
  18012. if (!localRange) {
  18013. continue;
  18014. }
  18015. var range = {};
  18016. range.name = name;
  18017. range.from = localRange.from;
  18018. range.to = localRange.to;
  18019. serializationRanges.push(range);
  18020. }
  18021. return serializationRanges;
  18022. };
  18023. /**
  18024. * Computes the world matrix of the node
  18025. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18026. * @returns the world matrix
  18027. */
  18028. Node.prototype.computeWorldMatrix = function (force) {
  18029. return BABYLON.Matrix.Identity();
  18030. };
  18031. /**
  18032. * Releases resources associated with this node.
  18033. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18034. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18035. */
  18036. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18037. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18038. if (!doNotRecurse) {
  18039. var nodes = this.getDescendants(true);
  18040. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18041. var node = nodes_1[_i];
  18042. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18043. }
  18044. }
  18045. else {
  18046. var transformNodes = this.getChildTransformNodes(true);
  18047. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18048. var transformNode = transformNodes_1[_a];
  18049. transformNode.parent = null;
  18050. transformNode.computeWorldMatrix(true);
  18051. }
  18052. }
  18053. this.parent = null;
  18054. // Callback
  18055. this.onDisposeObservable.notifyObservers(this);
  18056. this.onDisposeObservable.clear();
  18057. // Behaviors
  18058. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18059. var behavior = _c[_b];
  18060. behavior.detach();
  18061. }
  18062. this._behaviors = [];
  18063. this._isDisposed = true;
  18064. };
  18065. /**
  18066. * Parse animation range data from a serialization object and store them into a given node
  18067. * @param node defines where to store the animation ranges
  18068. * @param parsedNode defines the serialization object to read data from
  18069. * @param scene defines the hosting scene
  18070. */
  18071. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18072. if (parsedNode.ranges) {
  18073. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18074. var data = parsedNode.ranges[index];
  18075. node.createAnimationRange(data.name, data.from, data.to);
  18076. }
  18077. }
  18078. };
  18079. __decorate([
  18080. BABYLON.serialize()
  18081. ], Node.prototype, "name", void 0);
  18082. __decorate([
  18083. BABYLON.serialize()
  18084. ], Node.prototype, "id", void 0);
  18085. __decorate([
  18086. BABYLON.serialize()
  18087. ], Node.prototype, "uniqueId", void 0);
  18088. __decorate([
  18089. BABYLON.serialize()
  18090. ], Node.prototype, "state", void 0);
  18091. __decorate([
  18092. BABYLON.serialize()
  18093. ], Node.prototype, "metadata", void 0);
  18094. return Node;
  18095. }());
  18096. BABYLON.Node = Node;
  18097. })(BABYLON || (BABYLON = {}));
  18098. //# sourceMappingURL=babylon.node.js.map
  18099. var BABYLON;
  18100. (function (BABYLON) {
  18101. var BoundingSphere = /** @class */ (function () {
  18102. /**
  18103. * Creates a new bounding sphere
  18104. * @param min defines the minimum vector (in local space)
  18105. * @param max defines the maximum vector (in local space)
  18106. */
  18107. function BoundingSphere(min, max) {
  18108. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18109. this.reConstruct(min, max);
  18110. }
  18111. /**
  18112. * Recreates the entire bounding sphere from scratch
  18113. * @param min defines the new minimum vector (in local space)
  18114. * @param max defines the new maximum vector (in local space)
  18115. */
  18116. BoundingSphere.prototype.reConstruct = function (min, max) {
  18117. this.minimum = min.clone();
  18118. this.maximum = max.clone();
  18119. var distance = BABYLON.Vector3.Distance(min, max);
  18120. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18121. this.radius = distance * 0.5;
  18122. this.centerWorld = BABYLON.Vector3.Zero();
  18123. this._update(BABYLON.Matrix.Identity());
  18124. };
  18125. // Methods
  18126. BoundingSphere.prototype._update = function (world) {
  18127. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18128. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18129. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18130. };
  18131. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18132. for (var i = 0; i < 6; i++) {
  18133. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18134. return false;
  18135. }
  18136. return true;
  18137. };
  18138. BoundingSphere.prototype.intersectsPoint = function (point) {
  18139. var x = this.centerWorld.x - point.x;
  18140. var y = this.centerWorld.y - point.y;
  18141. var z = this.centerWorld.z - point.z;
  18142. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18143. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18144. return false;
  18145. return true;
  18146. };
  18147. // Statics
  18148. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18149. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18150. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18151. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18152. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18153. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18154. return false;
  18155. return true;
  18156. };
  18157. return BoundingSphere;
  18158. }());
  18159. BABYLON.BoundingSphere = BoundingSphere;
  18160. })(BABYLON || (BABYLON = {}));
  18161. //# sourceMappingURL=babylon.boundingSphere.js.map
  18162. var BABYLON;
  18163. (function (BABYLON) {
  18164. var BoundingBox = /** @class */ (function () {
  18165. /**
  18166. * Creates a new bounding box
  18167. * @param min defines the minimum vector (in local space)
  18168. * @param max defines the maximum vector (in local space)
  18169. */
  18170. function BoundingBox(min, max) {
  18171. this.vectorsWorld = new Array();
  18172. this.reConstruct(min, max);
  18173. }
  18174. // Methods
  18175. /**
  18176. * Recreates the entire bounding box from scratch
  18177. * @param min defines the new minimum vector (in local space)
  18178. * @param max defines the new maximum vector (in local space)
  18179. */
  18180. BoundingBox.prototype.reConstruct = function (min, max) {
  18181. this.minimum = min.clone();
  18182. this.maximum = max.clone();
  18183. // Bounding vectors
  18184. this.vectors = new Array();
  18185. this.vectors.push(this.minimum.clone());
  18186. this.vectors.push(this.maximum.clone());
  18187. this.vectors.push(this.minimum.clone());
  18188. this.vectors[2].x = this.maximum.x;
  18189. this.vectors.push(this.minimum.clone());
  18190. this.vectors[3].y = this.maximum.y;
  18191. this.vectors.push(this.minimum.clone());
  18192. this.vectors[4].z = this.maximum.z;
  18193. this.vectors.push(this.maximum.clone());
  18194. this.vectors[5].z = this.minimum.z;
  18195. this.vectors.push(this.maximum.clone());
  18196. this.vectors[6].x = this.minimum.x;
  18197. this.vectors.push(this.maximum.clone());
  18198. this.vectors[7].y = this.minimum.y;
  18199. // OBB
  18200. this.center = this.maximum.add(this.minimum).scale(0.5);
  18201. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18202. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18203. // World
  18204. for (var index = 0; index < this.vectors.length; index++) {
  18205. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18206. }
  18207. this.minimumWorld = BABYLON.Vector3.Zero();
  18208. this.maximumWorld = BABYLON.Vector3.Zero();
  18209. this.centerWorld = BABYLON.Vector3.Zero();
  18210. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18211. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18212. };
  18213. BoundingBox.prototype.getWorldMatrix = function () {
  18214. return this._worldMatrix;
  18215. };
  18216. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18217. this._worldMatrix.copyFrom(matrix);
  18218. return this;
  18219. };
  18220. BoundingBox.prototype._update = function (world) {
  18221. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18222. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18223. for (var index = 0; index < this.vectors.length; index++) {
  18224. var v = this.vectorsWorld[index];
  18225. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18226. if (v.x < this.minimumWorld.x)
  18227. this.minimumWorld.x = v.x;
  18228. if (v.y < this.minimumWorld.y)
  18229. this.minimumWorld.y = v.y;
  18230. if (v.z < this.minimumWorld.z)
  18231. this.minimumWorld.z = v.z;
  18232. if (v.x > this.maximumWorld.x)
  18233. this.maximumWorld.x = v.x;
  18234. if (v.y > this.maximumWorld.y)
  18235. this.maximumWorld.y = v.y;
  18236. if (v.z > this.maximumWorld.z)
  18237. this.maximumWorld.z = v.z;
  18238. }
  18239. // Extend
  18240. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18241. this.extendSizeWorld.scaleInPlace(0.5);
  18242. // OBB
  18243. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18244. this.centerWorld.scaleInPlace(0.5);
  18245. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18246. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18247. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18248. this._worldMatrix = world;
  18249. };
  18250. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18251. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18252. };
  18253. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18254. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18255. };
  18256. BoundingBox.prototype.intersectsPoint = function (point) {
  18257. var delta = -BABYLON.Epsilon;
  18258. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18259. return false;
  18260. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18261. return false;
  18262. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18263. return false;
  18264. return true;
  18265. };
  18266. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18267. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18268. };
  18269. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18270. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18271. return false;
  18272. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18273. return false;
  18274. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18275. return false;
  18276. return true;
  18277. };
  18278. // Statics
  18279. BoundingBox.Intersects = function (box0, box1) {
  18280. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18281. return false;
  18282. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18283. return false;
  18284. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18285. return false;
  18286. return true;
  18287. };
  18288. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18289. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18290. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18291. return (num <= (sphereRadius * sphereRadius));
  18292. };
  18293. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18294. for (var p = 0; p < 6; p++) {
  18295. for (var i = 0; i < 8; i++) {
  18296. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18297. return false;
  18298. }
  18299. }
  18300. }
  18301. return true;
  18302. };
  18303. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18304. for (var p = 0; p < 6; p++) {
  18305. var inCount = 8;
  18306. for (var i = 0; i < 8; i++) {
  18307. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18308. --inCount;
  18309. }
  18310. else {
  18311. break;
  18312. }
  18313. }
  18314. if (inCount === 0)
  18315. return false;
  18316. }
  18317. return true;
  18318. };
  18319. return BoundingBox;
  18320. }());
  18321. BABYLON.BoundingBox = BoundingBox;
  18322. })(BABYLON || (BABYLON = {}));
  18323. //# sourceMappingURL=babylon.boundingBox.js.map
  18324. var BABYLON;
  18325. (function (BABYLON) {
  18326. var computeBoxExtents = function (axis, box) {
  18327. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18328. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18329. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18330. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18331. var r = r0 + r1 + r2;
  18332. return {
  18333. min: p - r,
  18334. max: p + r
  18335. };
  18336. };
  18337. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18338. var axisOverlap = function (axis, box0, box1) {
  18339. var result0 = computeBoxExtents(axis, box0);
  18340. var result1 = computeBoxExtents(axis, box1);
  18341. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18342. };
  18343. var BoundingInfo = /** @class */ (function () {
  18344. function BoundingInfo(minimum, maximum) {
  18345. this.minimum = minimum;
  18346. this.maximum = maximum;
  18347. this._isLocked = false;
  18348. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18349. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18350. }
  18351. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18352. get: function () {
  18353. return this._isLocked;
  18354. },
  18355. set: function (value) {
  18356. this._isLocked = value;
  18357. },
  18358. enumerable: true,
  18359. configurable: true
  18360. });
  18361. // Methods
  18362. BoundingInfo.prototype.update = function (world) {
  18363. if (this._isLocked) {
  18364. return;
  18365. }
  18366. this.boundingBox._update(world);
  18367. this.boundingSphere._update(world);
  18368. };
  18369. /**
  18370. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18371. * @param center New center of the bounding info
  18372. * @param extend New extend of the bounding info
  18373. */
  18374. BoundingInfo.prototype.centerOn = function (center, extend) {
  18375. this.minimum = center.subtract(extend);
  18376. this.maximum = center.add(extend);
  18377. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18378. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18379. return this;
  18380. };
  18381. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18382. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18383. return false;
  18384. return this.boundingBox.isInFrustum(frustumPlanes);
  18385. };
  18386. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18387. /**
  18388. * Gets the world distance between the min and max points of the bounding box
  18389. */
  18390. get: function () {
  18391. var boundingBox = this.boundingBox;
  18392. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18393. return size.length();
  18394. },
  18395. enumerable: true,
  18396. configurable: true
  18397. });
  18398. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18399. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18400. };
  18401. BoundingInfo.prototype._checkCollision = function (collider) {
  18402. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18403. };
  18404. BoundingInfo.prototype.intersectsPoint = function (point) {
  18405. if (!this.boundingSphere.centerWorld) {
  18406. return false;
  18407. }
  18408. if (!this.boundingSphere.intersectsPoint(point)) {
  18409. return false;
  18410. }
  18411. if (!this.boundingBox.intersectsPoint(point)) {
  18412. return false;
  18413. }
  18414. return true;
  18415. };
  18416. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18417. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18418. return false;
  18419. }
  18420. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18421. return false;
  18422. }
  18423. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18424. return false;
  18425. }
  18426. if (!precise) {
  18427. return true;
  18428. }
  18429. var box0 = this.boundingBox;
  18430. var box1 = boundingInfo.boundingBox;
  18431. if (!axisOverlap(box0.directions[0], box0, box1))
  18432. return false;
  18433. if (!axisOverlap(box0.directions[1], box0, box1))
  18434. return false;
  18435. if (!axisOverlap(box0.directions[2], box0, box1))
  18436. return false;
  18437. if (!axisOverlap(box1.directions[0], box0, box1))
  18438. return false;
  18439. if (!axisOverlap(box1.directions[1], box0, box1))
  18440. return false;
  18441. if (!axisOverlap(box1.directions[2], box0, box1))
  18442. return false;
  18443. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18444. return false;
  18445. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18446. return false;
  18447. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18448. return false;
  18449. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18450. return false;
  18451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18452. return false;
  18453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18454. return false;
  18455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18456. return false;
  18457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18458. return false;
  18459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18460. return false;
  18461. return true;
  18462. };
  18463. return BoundingInfo;
  18464. }());
  18465. BABYLON.BoundingInfo = BoundingInfo;
  18466. })(BABYLON || (BABYLON = {}));
  18467. //# sourceMappingURL=babylon.boundingInfo.js.map
  18468. var BABYLON;
  18469. (function (BABYLON) {
  18470. var TransformNode = /** @class */ (function (_super) {
  18471. __extends(TransformNode, _super);
  18472. function TransformNode(name, scene, isPure) {
  18473. if (scene === void 0) { scene = null; }
  18474. if (isPure === void 0) { isPure = true; }
  18475. var _this = _super.call(this, name, scene) || this;
  18476. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18477. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18478. _this._up = new BABYLON.Vector3(0, 1, 0);
  18479. _this._right = new BABYLON.Vector3(1, 0, 0);
  18480. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18481. // Properties
  18482. _this._rotation = BABYLON.Vector3.Zero();
  18483. _this._scaling = BABYLON.Vector3.One();
  18484. _this._isDirty = false;
  18485. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18486. _this.scalingDeterminant = 1;
  18487. _this.infiniteDistance = false;
  18488. /**
  18489. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18490. * By default the system will update normals to compensate
  18491. */
  18492. _this.ignoreNonUniformScaling = false;
  18493. _this.position = BABYLON.Vector3.Zero();
  18494. _this._localWorld = BABYLON.Matrix.Zero();
  18495. _this._worldMatrix = BABYLON.Matrix.Zero();
  18496. _this._worldMatrixDeterminant = 0;
  18497. _this._absolutePosition = BABYLON.Vector3.Zero();
  18498. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18499. _this._postMultiplyPivotMatrix = false;
  18500. _this._isWorldMatrixFrozen = false;
  18501. /**
  18502. * An event triggered after the world matrix is updated
  18503. */
  18504. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18505. _this._nonUniformScaling = false;
  18506. if (isPure) {
  18507. _this.getScene().addTransformNode(_this);
  18508. }
  18509. return _this;
  18510. }
  18511. /**
  18512. * Gets a string idenfifying the name of the class
  18513. * @returns "TransformNode" string
  18514. */
  18515. TransformNode.prototype.getClassName = function () {
  18516. return "TransformNode";
  18517. };
  18518. Object.defineProperty(TransformNode.prototype, "rotation", {
  18519. /**
  18520. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18521. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18522. * Default : (0.0, 0.0, 0.0)
  18523. */
  18524. get: function () {
  18525. return this._rotation;
  18526. },
  18527. set: function (newRotation) {
  18528. this._rotation = newRotation;
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. Object.defineProperty(TransformNode.prototype, "scaling", {
  18534. /**
  18535. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18536. * Default : (1.0, 1.0, 1.0)
  18537. */
  18538. get: function () {
  18539. return this._scaling;
  18540. },
  18541. /**
  18542. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18543. * Default : (1.0, 1.0, 1.0)
  18544. */
  18545. set: function (newScaling) {
  18546. this._scaling = newScaling;
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18552. /**
  18553. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18554. * It's null by default.
  18555. * 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)
  18556. */
  18557. get: function () {
  18558. return this._rotationQuaternion;
  18559. },
  18560. set: function (quaternion) {
  18561. this._rotationQuaternion = quaternion;
  18562. //reset the rotation vector.
  18563. if (quaternion && this.rotation.length()) {
  18564. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18565. }
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. Object.defineProperty(TransformNode.prototype, "forward", {
  18571. /**
  18572. * The forward direction of that transform in world space.
  18573. */
  18574. get: function () {
  18575. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18576. },
  18577. enumerable: true,
  18578. configurable: true
  18579. });
  18580. Object.defineProperty(TransformNode.prototype, "up", {
  18581. /**
  18582. * The up direction of that transform in world space.
  18583. */
  18584. get: function () {
  18585. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18586. },
  18587. enumerable: true,
  18588. configurable: true
  18589. });
  18590. Object.defineProperty(TransformNode.prototype, "right", {
  18591. /**
  18592. * The right direction of that transform in world space.
  18593. */
  18594. get: function () {
  18595. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. /**
  18601. * Returns the latest update of the World matrix
  18602. * Returns a Matrix.
  18603. */
  18604. TransformNode.prototype.getWorldMatrix = function () {
  18605. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18606. this.computeWorldMatrix();
  18607. }
  18608. return this._worldMatrix;
  18609. };
  18610. /** @hidden */
  18611. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18612. return this._worldMatrixDeterminant;
  18613. };
  18614. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18615. /**
  18616. * Returns directly the latest state of the mesh World matrix.
  18617. * A Matrix is returned.
  18618. */
  18619. get: function () {
  18620. return this._worldMatrix;
  18621. },
  18622. enumerable: true,
  18623. configurable: true
  18624. });
  18625. /**
  18626. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18627. * Returns the TransformNode.
  18628. */
  18629. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18630. this._poseMatrix.copyFrom(matrix);
  18631. return this;
  18632. };
  18633. /**
  18634. * Returns the mesh Pose matrix.
  18635. * Returned object : Matrix
  18636. */
  18637. TransformNode.prototype.getPoseMatrix = function () {
  18638. return this._poseMatrix;
  18639. };
  18640. TransformNode.prototype._isSynchronized = function () {
  18641. if (this._isDirty) {
  18642. return false;
  18643. }
  18644. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18645. return false;
  18646. if (this._cache.pivotMatrixUpdated) {
  18647. return false;
  18648. }
  18649. if (this.infiniteDistance) {
  18650. return false;
  18651. }
  18652. if (!this._cache.position.equals(this.position))
  18653. return false;
  18654. if (this.rotationQuaternion) {
  18655. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18656. return false;
  18657. }
  18658. if (!this._cache.rotation.equals(this.rotation))
  18659. return false;
  18660. if (!this._cache.scaling.equals(this.scaling))
  18661. return false;
  18662. return true;
  18663. };
  18664. TransformNode.prototype._initCache = function () {
  18665. _super.prototype._initCache.call(this);
  18666. this._cache.localMatrixUpdated = false;
  18667. this._cache.position = BABYLON.Vector3.Zero();
  18668. this._cache.scaling = BABYLON.Vector3.Zero();
  18669. this._cache.rotation = BABYLON.Vector3.Zero();
  18670. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18671. this._cache.billboardMode = -1;
  18672. };
  18673. TransformNode.prototype.markAsDirty = function (property) {
  18674. if (property === "rotation") {
  18675. this.rotationQuaternion = null;
  18676. }
  18677. this._currentRenderId = Number.MAX_VALUE;
  18678. this._isDirty = true;
  18679. return this;
  18680. };
  18681. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18682. /**
  18683. * Returns the current mesh absolute position.
  18684. * Retuns a Vector3.
  18685. */
  18686. get: function () {
  18687. return this._absolutePosition;
  18688. },
  18689. enumerable: true,
  18690. configurable: true
  18691. });
  18692. /**
  18693. * Sets a new matrix to apply before all other transformation
  18694. * @param matrix defines the transform matrix
  18695. * @returns the current TransformNode
  18696. */
  18697. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18698. return this.setPivotMatrix(matrix, false);
  18699. };
  18700. /**
  18701. * Sets a new pivot matrix to the current node
  18702. * @param matrix defines the new pivot matrix to use
  18703. * @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
  18704. * @returns the current TransformNode
  18705. */
  18706. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18707. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18708. this._pivotMatrix = matrix.clone();
  18709. this._cache.pivotMatrixUpdated = true;
  18710. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18711. if (this._postMultiplyPivotMatrix) {
  18712. if (!this._pivotMatrixInverse) {
  18713. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18714. }
  18715. else {
  18716. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18717. }
  18718. }
  18719. return this;
  18720. };
  18721. /**
  18722. * Returns the mesh pivot matrix.
  18723. * Default : Identity.
  18724. * A Matrix is returned.
  18725. */
  18726. TransformNode.prototype.getPivotMatrix = function () {
  18727. return this._pivotMatrix;
  18728. };
  18729. /**
  18730. * Prevents the World matrix to be computed any longer.
  18731. * Returns the TransformNode.
  18732. */
  18733. TransformNode.prototype.freezeWorldMatrix = function () {
  18734. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18735. this.computeWorldMatrix(true);
  18736. this._isWorldMatrixFrozen = true;
  18737. return this;
  18738. };
  18739. /**
  18740. * Allows back the World matrix computation.
  18741. * Returns the TransformNode.
  18742. */
  18743. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18744. this._isWorldMatrixFrozen = false;
  18745. this.computeWorldMatrix(true);
  18746. return this;
  18747. };
  18748. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18749. /**
  18750. * True if the World matrix has been frozen.
  18751. * Returns a boolean.
  18752. */
  18753. get: function () {
  18754. return this._isWorldMatrixFrozen;
  18755. },
  18756. enumerable: true,
  18757. configurable: true
  18758. });
  18759. /**
  18760. * Retuns the mesh absolute position in the World.
  18761. * Returns a Vector3.
  18762. */
  18763. TransformNode.prototype.getAbsolutePosition = function () {
  18764. this.computeWorldMatrix();
  18765. return this._absolutePosition;
  18766. };
  18767. /**
  18768. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18769. * Returns the TransformNode.
  18770. */
  18771. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18772. if (!absolutePosition) {
  18773. return this;
  18774. }
  18775. var absolutePositionX;
  18776. var absolutePositionY;
  18777. var absolutePositionZ;
  18778. if (absolutePosition.x === undefined) {
  18779. if (arguments.length < 3) {
  18780. return this;
  18781. }
  18782. absolutePositionX = arguments[0];
  18783. absolutePositionY = arguments[1];
  18784. absolutePositionZ = arguments[2];
  18785. }
  18786. else {
  18787. absolutePositionX = absolutePosition.x;
  18788. absolutePositionY = absolutePosition.y;
  18789. absolutePositionZ = absolutePosition.z;
  18790. }
  18791. if (this.parent) {
  18792. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18793. invertParentWorldMatrix.invert();
  18794. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18795. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18796. }
  18797. else {
  18798. this.position.x = absolutePositionX;
  18799. this.position.y = absolutePositionY;
  18800. this.position.z = absolutePositionZ;
  18801. }
  18802. return this;
  18803. };
  18804. /**
  18805. * Sets the mesh position in its local space.
  18806. * Returns the TransformNode.
  18807. */
  18808. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18809. this.computeWorldMatrix();
  18810. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18811. return this;
  18812. };
  18813. /**
  18814. * Returns the mesh position in the local space from the current World matrix values.
  18815. * Returns a new Vector3.
  18816. */
  18817. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18818. this.computeWorldMatrix();
  18819. var invLocalWorldMatrix = this._localWorld.clone();
  18820. invLocalWorldMatrix.invert();
  18821. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18822. };
  18823. /**
  18824. * Translates the mesh along the passed Vector3 in its local space.
  18825. * Returns the TransformNode.
  18826. */
  18827. TransformNode.prototype.locallyTranslate = function (vector3) {
  18828. this.computeWorldMatrix(true);
  18829. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18830. return this;
  18831. };
  18832. /**
  18833. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18834. * @param targetPoint the position (must be in same space as current mesh) to look at
  18835. * @param yawCor optional yaw (y-axis) correction in radians
  18836. * @param pitchCor optional pitch (x-axis) correction in radians
  18837. * @param rollCor optional roll (z-axis) correction in radians
  18838. * @param space the choosen space of the target
  18839. * @returns the TransformNode.
  18840. */
  18841. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18842. if (yawCor === void 0) { yawCor = 0; }
  18843. if (pitchCor === void 0) { pitchCor = 0; }
  18844. if (rollCor === void 0) { rollCor = 0; }
  18845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18846. var dv = TransformNode._lookAtVectorCache;
  18847. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18848. targetPoint.subtractToRef(pos, dv);
  18849. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18850. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18851. var pitch = Math.atan2(dv.y, len);
  18852. if (this.rotationQuaternion) {
  18853. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18854. }
  18855. else {
  18856. this.rotation.x = pitch + pitchCor;
  18857. this.rotation.y = yaw + yawCor;
  18858. this.rotation.z = rollCor;
  18859. }
  18860. return this;
  18861. };
  18862. /**
  18863. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18864. * This Vector3 is expressed in the World space.
  18865. */
  18866. TransformNode.prototype.getDirection = function (localAxis) {
  18867. var result = BABYLON.Vector3.Zero();
  18868. this.getDirectionToRef(localAxis, result);
  18869. return result;
  18870. };
  18871. /**
  18872. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18873. * localAxis is expressed in the mesh local space.
  18874. * result is computed in the Wordl space from the mesh World matrix.
  18875. * Returns the TransformNode.
  18876. */
  18877. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18878. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18879. return this;
  18880. };
  18881. /**
  18882. * Sets a new pivot point to the current node
  18883. * @param point defines the new pivot point to use
  18884. * @param space defines if the point is in world or local space (local by default)
  18885. * @returns the current TransformNode
  18886. */
  18887. TransformNode.prototype.setPivotPoint = function (point, space) {
  18888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18889. if (this.getScene().getRenderId() == 0) {
  18890. this.computeWorldMatrix(true);
  18891. }
  18892. var wm = this.getWorldMatrix();
  18893. if (space == BABYLON.Space.WORLD) {
  18894. var tmat = BABYLON.Tmp.Matrix[0];
  18895. wm.invertToRef(tmat);
  18896. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18897. }
  18898. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18899. };
  18900. /**
  18901. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18902. */
  18903. TransformNode.prototype.getPivotPoint = function () {
  18904. var point = BABYLON.Vector3.Zero();
  18905. this.getPivotPointToRef(point);
  18906. return point;
  18907. };
  18908. /**
  18909. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18910. * Returns the TransformNode.
  18911. */
  18912. TransformNode.prototype.getPivotPointToRef = function (result) {
  18913. result.x = -this._pivotMatrix.m[12];
  18914. result.y = -this._pivotMatrix.m[13];
  18915. result.z = -this._pivotMatrix.m[14];
  18916. return this;
  18917. };
  18918. /**
  18919. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18920. */
  18921. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18922. var point = BABYLON.Vector3.Zero();
  18923. this.getAbsolutePivotPointToRef(point);
  18924. return point;
  18925. };
  18926. /**
  18927. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18928. * Returns the TransformNode.
  18929. */
  18930. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18931. result.x = this._pivotMatrix.m[12];
  18932. result.y = this._pivotMatrix.m[13];
  18933. result.z = this._pivotMatrix.m[14];
  18934. this.getPivotPointToRef(result);
  18935. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18936. return this;
  18937. };
  18938. /**
  18939. * Defines the passed node as the parent of the current node.
  18940. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18941. * Returns the TransformNode.
  18942. */
  18943. TransformNode.prototype.setParent = function (node) {
  18944. if (node === null) {
  18945. var rotation = BABYLON.Tmp.Quaternion[0];
  18946. var position = BABYLON.Tmp.Vector3[0];
  18947. var scale = BABYLON.Tmp.Vector3[1];
  18948. if (this.parent && this.parent.computeWorldMatrix) {
  18949. this.parent.computeWorldMatrix(true);
  18950. }
  18951. this.computeWorldMatrix(true);
  18952. this.getWorldMatrix().decompose(scale, rotation, position);
  18953. if (this.rotationQuaternion) {
  18954. this.rotationQuaternion.copyFrom(rotation);
  18955. }
  18956. else {
  18957. rotation.toEulerAnglesToRef(this.rotation);
  18958. }
  18959. this.scaling.x = scale.x;
  18960. this.scaling.y = scale.y;
  18961. this.scaling.z = scale.z;
  18962. this.position.x = position.x;
  18963. this.position.y = position.y;
  18964. this.position.z = position.z;
  18965. }
  18966. else {
  18967. var rotation = BABYLON.Tmp.Quaternion[0];
  18968. var position = BABYLON.Tmp.Vector3[0];
  18969. var scale = BABYLON.Tmp.Vector3[1];
  18970. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18971. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18972. this.computeWorldMatrix(true);
  18973. node.computeWorldMatrix(true);
  18974. node.getWorldMatrix().invertToRef(invParentMatrix);
  18975. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18976. diffMatrix.decompose(scale, rotation, position);
  18977. if (this.rotationQuaternion) {
  18978. this.rotationQuaternion.copyFrom(rotation);
  18979. }
  18980. else {
  18981. rotation.toEulerAnglesToRef(this.rotation);
  18982. }
  18983. this.position.x = position.x;
  18984. this.position.y = position.y;
  18985. this.position.z = position.z;
  18986. this.scaling.x = scale.x;
  18987. this.scaling.y = scale.y;
  18988. this.scaling.z = scale.z;
  18989. }
  18990. this.parent = node;
  18991. return this;
  18992. };
  18993. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18994. get: function () {
  18995. return this._nonUniformScaling;
  18996. },
  18997. enumerable: true,
  18998. configurable: true
  18999. });
  19000. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19001. if (this._nonUniformScaling === value) {
  19002. return false;
  19003. }
  19004. this._nonUniformScaling = value;
  19005. return true;
  19006. };
  19007. /**
  19008. * Attach the current TransformNode to another TransformNode associated with a bone
  19009. * @param bone Bone affecting the TransformNode
  19010. * @param affectedTransformNode TransformNode associated with the bone
  19011. */
  19012. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19013. this._transformToBoneReferal = affectedTransformNode;
  19014. this.parent = bone;
  19015. if (bone.getWorldMatrix().determinant() < 0) {
  19016. this.scalingDeterminant *= -1;
  19017. }
  19018. return this;
  19019. };
  19020. TransformNode.prototype.detachFromBone = function () {
  19021. if (!this.parent) {
  19022. return this;
  19023. }
  19024. if (this.parent.getWorldMatrix().determinant() < 0) {
  19025. this.scalingDeterminant *= -1;
  19026. }
  19027. this._transformToBoneReferal = null;
  19028. this.parent = null;
  19029. return this;
  19030. };
  19031. /**
  19032. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19033. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19034. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19035. * The passed axis is also normalized.
  19036. * Returns the TransformNode.
  19037. */
  19038. TransformNode.prototype.rotate = function (axis, amount, space) {
  19039. axis.normalize();
  19040. if (!this.rotationQuaternion) {
  19041. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19042. this.rotation = BABYLON.Vector3.Zero();
  19043. }
  19044. var rotationQuaternion;
  19045. if (!space || space === BABYLON.Space.LOCAL) {
  19046. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19047. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19048. }
  19049. else {
  19050. if (this.parent) {
  19051. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19052. invertParentWorldMatrix.invert();
  19053. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19054. }
  19055. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19056. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19057. }
  19058. return this;
  19059. };
  19060. /**
  19061. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19062. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19063. * The passed axis is also normalized.
  19064. * Returns the TransformNode.
  19065. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19066. */
  19067. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19068. axis.normalize();
  19069. if (!this.rotationQuaternion) {
  19070. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19071. this.rotation.copyFromFloats(0, 0, 0);
  19072. }
  19073. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19074. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19075. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19076. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19077. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19078. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19079. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19080. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19081. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19082. return this;
  19083. };
  19084. /**
  19085. * Translates the mesh along the axis vector for the passed distance in the given space.
  19086. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19087. * Returns the TransformNode.
  19088. */
  19089. TransformNode.prototype.translate = function (axis, distance, space) {
  19090. var displacementVector = axis.scale(distance);
  19091. if (!space || space === BABYLON.Space.LOCAL) {
  19092. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19093. this.setPositionWithLocalVector(tempV3);
  19094. }
  19095. else {
  19096. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19097. }
  19098. return this;
  19099. };
  19100. /**
  19101. * Adds a rotation step to the mesh current rotation.
  19102. * x, y, z are Euler angles expressed in radians.
  19103. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19104. * This means this rotation is made in the mesh local space only.
  19105. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19106. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19107. * ```javascript
  19108. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19109. * ```
  19110. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19111. * 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.
  19112. * Returns the TransformNode.
  19113. */
  19114. TransformNode.prototype.addRotation = function (x, y, z) {
  19115. var rotationQuaternion;
  19116. if (this.rotationQuaternion) {
  19117. rotationQuaternion = this.rotationQuaternion;
  19118. }
  19119. else {
  19120. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19121. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19122. }
  19123. var accumulation = BABYLON.Tmp.Quaternion[0];
  19124. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19125. rotationQuaternion.multiplyInPlace(accumulation);
  19126. if (!this.rotationQuaternion) {
  19127. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19128. }
  19129. return this;
  19130. };
  19131. /**
  19132. * Computes the mesh World matrix and returns it.
  19133. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19134. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19135. * If the parameter `force`is set to `true`, the actual computation is done.
  19136. * Returns the mesh World Matrix.
  19137. */
  19138. TransformNode.prototype.computeWorldMatrix = function (force) {
  19139. if (this._isWorldMatrixFrozen) {
  19140. return this._worldMatrix;
  19141. }
  19142. if (!force && this.isSynchronized(true)) {
  19143. this._currentRenderId = this.getScene().getRenderId();
  19144. return this._worldMatrix;
  19145. }
  19146. this._cache.position.copyFrom(this.position);
  19147. this._cache.scaling.copyFrom(this.scaling);
  19148. this._cache.pivotMatrixUpdated = false;
  19149. this._cache.billboardMode = this.billboardMode;
  19150. this._currentRenderId = this.getScene().getRenderId();
  19151. this._childRenderId = this.getScene().getRenderId();
  19152. this._isDirty = false;
  19153. // Scaling
  19154. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19155. // Rotation
  19156. //rotate, if quaternion is set and rotation was used
  19157. if (this.rotationQuaternion) {
  19158. var len = this.rotation.length();
  19159. if (len) {
  19160. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19161. this.rotation.copyFromFloats(0, 0, 0);
  19162. }
  19163. }
  19164. if (this.rotationQuaternion) {
  19165. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19166. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19167. }
  19168. else {
  19169. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19170. this._cache.rotation.copyFrom(this.rotation);
  19171. }
  19172. // Translation
  19173. var camera = this.getScene().activeCamera;
  19174. if (this.infiniteDistance && !this.parent && camera) {
  19175. var cameraWorldMatrix = camera.getWorldMatrix();
  19176. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19177. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19178. }
  19179. else {
  19180. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19181. }
  19182. // Composing transformations
  19183. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19184. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19185. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19186. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19187. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19188. // Need to decompose each rotation here
  19189. var currentPosition = BABYLON.Tmp.Vector3[3];
  19190. if (this.parent && this.parent.getWorldMatrix) {
  19191. if (this._transformToBoneReferal) {
  19192. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19193. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19194. }
  19195. else {
  19196. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19197. }
  19198. }
  19199. else {
  19200. currentPosition.copyFrom(this.position);
  19201. }
  19202. currentPosition.subtractInPlace(camera.globalPosition);
  19203. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19204. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19205. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19206. }
  19207. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19208. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19209. }
  19210. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19211. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19212. }
  19213. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19214. }
  19215. else {
  19216. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19217. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19218. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19219. }
  19220. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19221. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19222. }
  19223. // Local world
  19224. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19225. // Parent
  19226. if (this.parent && this.parent.getWorldMatrix) {
  19227. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19228. if (this._transformToBoneReferal) {
  19229. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19230. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19231. }
  19232. else {
  19233. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19234. }
  19235. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19236. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19237. this._worldMatrix.copyFrom(this._localWorld);
  19238. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19239. }
  19240. else {
  19241. if (this._transformToBoneReferal) {
  19242. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19243. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19244. }
  19245. else {
  19246. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19247. }
  19248. }
  19249. this._markSyncedWithParent();
  19250. }
  19251. else {
  19252. this._worldMatrix.copyFrom(this._localWorld);
  19253. }
  19254. // Post multiply inverse of pivotMatrix
  19255. if (this._postMultiplyPivotMatrix) {
  19256. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19257. }
  19258. // Normal matrix
  19259. if (!this.ignoreNonUniformScaling) {
  19260. if (this.scaling.isNonUniform) {
  19261. this._updateNonUniformScalingState(true);
  19262. }
  19263. else if (this.parent && this.parent._nonUniformScaling) {
  19264. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19265. }
  19266. else {
  19267. this._updateNonUniformScalingState(false);
  19268. }
  19269. }
  19270. else {
  19271. this._updateNonUniformScalingState(false);
  19272. }
  19273. this._afterComputeWorldMatrix();
  19274. // Absolute position
  19275. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19276. // Callbacks
  19277. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19278. if (!this._poseMatrix) {
  19279. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19280. }
  19281. // Cache the determinant
  19282. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19283. return this._worldMatrix;
  19284. };
  19285. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19286. };
  19287. /**
  19288. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19289. * @param func: callback function to add
  19290. *
  19291. * Returns the TransformNode.
  19292. */
  19293. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19294. this.onAfterWorldMatrixUpdateObservable.add(func);
  19295. return this;
  19296. };
  19297. /**
  19298. * Removes a registered callback function.
  19299. * Returns the TransformNode.
  19300. */
  19301. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19302. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19303. return this;
  19304. };
  19305. /**
  19306. * Clone the current transform node
  19307. * Returns the new transform node
  19308. * @param name Name of the new clone
  19309. * @param newParent New parent for the clone
  19310. * @param doNotCloneChildren Do not clone children hierarchy
  19311. */
  19312. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19313. var _this = this;
  19314. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19315. result.name = name;
  19316. result.id = name;
  19317. if (newParent) {
  19318. result.parent = newParent;
  19319. }
  19320. if (!doNotCloneChildren) {
  19321. // Children
  19322. var directDescendants = this.getDescendants(true);
  19323. for (var index = 0; index < directDescendants.length; index++) {
  19324. var child = directDescendants[index];
  19325. if (child.clone) {
  19326. child.clone(name + "." + child.name, result);
  19327. }
  19328. }
  19329. }
  19330. return result;
  19331. };
  19332. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19333. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19334. serializationObject.type = this.getClassName();
  19335. // Parent
  19336. if (this.parent) {
  19337. serializationObject.parentId = this.parent.id;
  19338. }
  19339. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19340. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19341. }
  19342. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19343. serializationObject.isEnabled = this.isEnabled();
  19344. // Parent
  19345. if (this.parent) {
  19346. serializationObject.parentId = this.parent.id;
  19347. }
  19348. return serializationObject;
  19349. };
  19350. // Statics
  19351. /**
  19352. * Returns a new TransformNode object parsed from the source provided.
  19353. * The parameter `parsedMesh` is the source.
  19354. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19355. */
  19356. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19357. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19358. if (BABYLON.Tags) {
  19359. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19360. }
  19361. if (parsedTransformNode.localMatrix) {
  19362. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19363. }
  19364. else if (parsedTransformNode.pivotMatrix) {
  19365. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19366. }
  19367. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19368. // Parent
  19369. if (parsedTransformNode.parentId) {
  19370. transformNode._waitingParentId = parsedTransformNode.parentId;
  19371. }
  19372. return transformNode;
  19373. };
  19374. /**
  19375. * Releases resources associated with this transform node.
  19376. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19377. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19378. */
  19379. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19380. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19381. // Animations
  19382. this.getScene().stopAnimation(this);
  19383. // Remove from scene
  19384. this.getScene().removeTransformNode(this);
  19385. this.onAfterWorldMatrixUpdateObservable.clear();
  19386. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19387. };
  19388. // Statics
  19389. TransformNode.BILLBOARDMODE_NONE = 0;
  19390. TransformNode.BILLBOARDMODE_X = 1;
  19391. TransformNode.BILLBOARDMODE_Y = 2;
  19392. TransformNode.BILLBOARDMODE_Z = 4;
  19393. TransformNode.BILLBOARDMODE_ALL = 7;
  19394. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19395. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19396. __decorate([
  19397. BABYLON.serializeAsVector3()
  19398. ], TransformNode.prototype, "_rotation", void 0);
  19399. __decorate([
  19400. BABYLON.serializeAsQuaternion()
  19401. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19402. __decorate([
  19403. BABYLON.serializeAsVector3()
  19404. ], TransformNode.prototype, "_scaling", void 0);
  19405. __decorate([
  19406. BABYLON.serialize()
  19407. ], TransformNode.prototype, "billboardMode", void 0);
  19408. __decorate([
  19409. BABYLON.serialize()
  19410. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19411. __decorate([
  19412. BABYLON.serialize()
  19413. ], TransformNode.prototype, "infiniteDistance", void 0);
  19414. __decorate([
  19415. BABYLON.serialize()
  19416. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19417. __decorate([
  19418. BABYLON.serializeAsVector3()
  19419. ], TransformNode.prototype, "position", void 0);
  19420. return TransformNode;
  19421. }(BABYLON.Node));
  19422. BABYLON.TransformNode = TransformNode;
  19423. })(BABYLON || (BABYLON = {}));
  19424. //# sourceMappingURL=babylon.transformNode.js.map
  19425. var BABYLON;
  19426. (function (BABYLON) {
  19427. /**
  19428. * Class used to store all common mesh properties
  19429. */
  19430. var AbstractMesh = /** @class */ (function (_super) {
  19431. __extends(AbstractMesh, _super);
  19432. // Constructor
  19433. /**
  19434. * Creates a new AbstractMesh
  19435. * @param name defines the name of the mesh
  19436. * @param scene defines the hosting scene
  19437. */
  19438. function AbstractMesh(name, scene) {
  19439. if (scene === void 0) { scene = null; }
  19440. var _this = _super.call(this, name, scene, false) || this;
  19441. _this._facetNb = 0; // facet number
  19442. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19443. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19444. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19445. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19446. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19447. _this._subDiv = {
  19448. max: 1,
  19449. X: 1,
  19450. Y: 1,
  19451. Z: 1
  19452. };
  19453. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19454. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19455. // Events
  19456. /**
  19457. * An event triggered when this mesh collides with another one
  19458. */
  19459. _this.onCollideObservable = new BABYLON.Observable();
  19460. /**
  19461. * An event triggered when the collision's position changes
  19462. */
  19463. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19464. /**
  19465. * An event triggered when material is changed
  19466. */
  19467. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19468. // Properties
  19469. /**
  19470. * Gets or sets the orientation for POV movement & rotation
  19471. */
  19472. _this.definedFacingForward = true;
  19473. /**
  19474. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19475. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19476. * * 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.
  19477. * @see http://doc.babylonjs.com/features/occlusionquery
  19478. */
  19479. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19480. /**
  19481. * 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:
  19482. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19483. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19484. * * 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.
  19485. * @see http://doc.babylonjs.com/features/occlusionquery
  19486. */
  19487. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19488. /**
  19489. * 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.
  19490. * The default value is -1 which means don't break the query and wait till the result
  19491. * @see http://doc.babylonjs.com/features/occlusionquery
  19492. */
  19493. _this.occlusionRetryCount = -1;
  19494. _this._occlusionInternalRetryCounter = 0;
  19495. _this._isOccluded = false;
  19496. _this._isOcclusionQueryInProgress = false;
  19497. _this._visibility = 1.0;
  19498. /** Gets or sets the alpha index used to sort transparent meshes
  19499. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19500. */
  19501. _this.alphaIndex = Number.MAX_VALUE;
  19502. /**
  19503. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19504. */
  19505. _this.isVisible = true;
  19506. /**
  19507. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19508. */
  19509. _this.isPickable = true;
  19510. /**
  19511. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19512. */
  19513. _this.showBoundingBox = false;
  19514. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19515. _this.showSubMeshesBoundingBox = false;
  19516. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19517. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19518. */
  19519. _this.isBlocker = false;
  19520. /**
  19521. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19522. */
  19523. _this.enablePointerMoveEvents = false;
  19524. /**
  19525. * Specifies the rendering group id for this mesh (0 by default)
  19526. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19527. */
  19528. _this.renderingGroupId = 0;
  19529. _this._receiveShadows = false;
  19530. /**
  19531. * Gets or sets a boolean indicating if the outline must be rendered as well
  19532. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19533. */
  19534. _this.renderOutline = false;
  19535. /** Defines color to use when rendering outline */
  19536. _this.outlineColor = BABYLON.Color3.Red();
  19537. /** Define width to use when rendering outline */
  19538. _this.outlineWidth = 0.02;
  19539. /**
  19540. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19541. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19542. */
  19543. _this.renderOverlay = false;
  19544. /** Defines color to use when rendering overlay */
  19545. _this.overlayColor = BABYLON.Color3.Red();
  19546. /** Defines alpha to use when rendering overlay */
  19547. _this.overlayAlpha = 0.5;
  19548. _this._hasVertexAlpha = false;
  19549. _this._useVertexColors = true;
  19550. _this._computeBonesUsingShaders = true;
  19551. _this._numBoneInfluencers = 4;
  19552. _this._applyFog = true;
  19553. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19554. _this.useOctreeForRenderingSelection = true;
  19555. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19556. _this.useOctreeForPicking = true;
  19557. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19558. _this.useOctreeForCollisions = true;
  19559. _this._layerMask = 0x0FFFFFFF;
  19560. /**
  19561. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19562. */
  19563. _this.alwaysSelectAsActiveMesh = false;
  19564. /**
  19565. * Gets or sets the current action manager
  19566. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19567. */
  19568. _this.actionManager = null;
  19569. /**
  19570. * Gets or sets impostor used for physic simulation
  19571. * @see http://doc.babylonjs.com/features/physics_engine
  19572. */
  19573. _this.physicsImpostor = null;
  19574. // Collisions
  19575. _this._checkCollisions = false;
  19576. _this._collisionMask = -1;
  19577. _this._collisionGroup = -1;
  19578. /**
  19579. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19580. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19581. */
  19582. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19583. /**
  19584. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19585. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19586. */
  19587. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19588. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19589. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19590. // Edges
  19591. /**
  19592. * Defines edge width used when edgesRenderer is enabled
  19593. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19594. */
  19595. _this.edgesWidth = 1;
  19596. /**
  19597. * Defines edge color used when edgesRenderer is enabled
  19598. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19599. */
  19600. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19601. // Cache
  19602. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19603. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19604. /** @hidden */
  19605. _this._renderId = 0;
  19606. /** @hidden */
  19607. _this._intersectionsInProgress = new Array();
  19608. /** @hidden */
  19609. _this._unIndexed = false;
  19610. /** @hidden */
  19611. _this._lightSources = new Array();
  19612. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19613. if (collidedMesh === void 0) { collidedMesh = null; }
  19614. //TODO move this to the collision coordinator!
  19615. if (_this.getScene().workerCollisions)
  19616. newPosition.multiplyInPlace(_this._collider._radius);
  19617. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19618. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19619. _this.position.addInPlace(_this._diffPositionForCollisions);
  19620. }
  19621. if (collidedMesh) {
  19622. _this.onCollideObservable.notifyObservers(collidedMesh);
  19623. }
  19624. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19625. };
  19626. _this.getScene().addMesh(_this);
  19627. _this._resyncLightSources();
  19628. return _this;
  19629. }
  19630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19631. /**
  19632. * No billboard
  19633. */
  19634. get: function () {
  19635. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19641. /** Billboard on X axis */
  19642. get: function () {
  19643. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19649. /** Billboard on Y axis */
  19650. get: function () {
  19651. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19657. /** Billboard on Z axis */
  19658. get: function () {
  19659. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19665. /** Billboard on all axes */
  19666. get: function () {
  19667. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19668. },
  19669. enumerable: true,
  19670. configurable: true
  19671. });
  19672. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19673. /**
  19674. * Gets the number of facets in the mesh
  19675. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19676. */
  19677. get: function () {
  19678. return this._facetNb;
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19684. /**
  19685. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19686. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19687. */
  19688. get: function () {
  19689. return this._partitioningSubdivisions;
  19690. },
  19691. set: function (nb) {
  19692. this._partitioningSubdivisions = nb;
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19698. /**
  19699. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19700. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19701. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19702. */
  19703. get: function () {
  19704. return this._partitioningBBoxRatio;
  19705. },
  19706. set: function (ratio) {
  19707. this._partitioningBBoxRatio = ratio;
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19713. /**
  19714. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19715. * Works only for updatable meshes.
  19716. * Doesn't work with multi-materials
  19717. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19718. */
  19719. get: function () {
  19720. return this._facetDepthSort;
  19721. },
  19722. set: function (sort) {
  19723. this._facetDepthSort = sort;
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19729. /**
  19730. * The location (Vector3) where the facet depth sort must be computed from.
  19731. * By default, the active camera position.
  19732. * Used only when facet depth sort is enabled
  19733. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19734. */
  19735. get: function () {
  19736. return this._facetDepthSortFrom;
  19737. },
  19738. set: function (location) {
  19739. this._facetDepthSortFrom = location;
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19745. /**
  19746. * gets a boolean indicating if facetData is enabled
  19747. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19748. */
  19749. get: function () {
  19750. return this._facetDataEnabled;
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. /** @hidden */
  19756. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19757. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19758. return false;
  19759. }
  19760. this._markSubMeshesAsMiscDirty();
  19761. return true;
  19762. };
  19763. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19764. /** Set a function to call when this mesh collides with another one */
  19765. set: function (callback) {
  19766. if (this._onCollideObserver) {
  19767. this.onCollideObservable.remove(this._onCollideObserver);
  19768. }
  19769. this._onCollideObserver = this.onCollideObservable.add(callback);
  19770. },
  19771. enumerable: true,
  19772. configurable: true
  19773. });
  19774. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19775. /** Set a function to call when the collision's position changes */
  19776. set: function (callback) {
  19777. if (this._onCollisionPositionChangeObserver) {
  19778. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19779. }
  19780. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19781. },
  19782. enumerable: true,
  19783. configurable: true
  19784. });
  19785. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19786. /**
  19787. * 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
  19788. * @see http://doc.babylonjs.com/features/occlusionquery
  19789. */
  19790. get: function () {
  19791. return this._isOccluded;
  19792. },
  19793. set: function (value) {
  19794. this._isOccluded = value;
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19800. /**
  19801. * Flag to check the progress status of the query
  19802. * @see http://doc.babylonjs.com/features/occlusionquery
  19803. */
  19804. get: function () {
  19805. return this._isOcclusionQueryInProgress;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19811. /**
  19812. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19813. */
  19814. get: function () {
  19815. return this._visibility;
  19816. },
  19817. /**
  19818. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19819. */
  19820. set: function (value) {
  19821. if (this._visibility === value) {
  19822. return;
  19823. }
  19824. this._visibility = value;
  19825. this._markSubMeshesAsMiscDirty();
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Object.defineProperty(AbstractMesh.prototype, "material", {
  19831. /** Gets or sets current material */
  19832. get: function () {
  19833. return this._material;
  19834. },
  19835. set: function (value) {
  19836. if (this._material === value) {
  19837. return;
  19838. }
  19839. this._material = value;
  19840. if (this.onMaterialChangedObservable.hasObservers) {
  19841. this.onMaterialChangedObservable.notifyObservers(this);
  19842. }
  19843. if (!this.subMeshes) {
  19844. return;
  19845. }
  19846. this._unBindEffect();
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19852. /**
  19853. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19854. * @see http://doc.babylonjs.com/babylon101/shadows
  19855. */
  19856. get: function () {
  19857. return this._receiveShadows;
  19858. },
  19859. set: function (value) {
  19860. if (this._receiveShadows === value) {
  19861. return;
  19862. }
  19863. this._receiveShadows = value;
  19864. this._markSubMeshesAsLightDirty();
  19865. },
  19866. enumerable: true,
  19867. configurable: true
  19868. });
  19869. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19870. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19871. get: function () {
  19872. return this._hasVertexAlpha;
  19873. },
  19874. set: function (value) {
  19875. if (this._hasVertexAlpha === value) {
  19876. return;
  19877. }
  19878. this._hasVertexAlpha = value;
  19879. this._markSubMeshesAsAttributesDirty();
  19880. this._markSubMeshesAsMiscDirty();
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19886. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19887. get: function () {
  19888. return this._useVertexColors;
  19889. },
  19890. set: function (value) {
  19891. if (this._useVertexColors === value) {
  19892. return;
  19893. }
  19894. this._useVertexColors = value;
  19895. this._markSubMeshesAsAttributesDirty();
  19896. },
  19897. enumerable: true,
  19898. configurable: true
  19899. });
  19900. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19901. /**
  19902. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19903. */
  19904. get: function () {
  19905. return this._computeBonesUsingShaders;
  19906. },
  19907. set: function (value) {
  19908. if (this._computeBonesUsingShaders === value) {
  19909. return;
  19910. }
  19911. this._computeBonesUsingShaders = value;
  19912. this._markSubMeshesAsAttributesDirty();
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19918. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19919. get: function () {
  19920. return this._numBoneInfluencers;
  19921. },
  19922. set: function (value) {
  19923. if (this._numBoneInfluencers === value) {
  19924. return;
  19925. }
  19926. this._numBoneInfluencers = value;
  19927. this._markSubMeshesAsAttributesDirty();
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19933. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19934. get: function () {
  19935. return this._applyFog;
  19936. },
  19937. set: function (value) {
  19938. if (this._applyFog === value) {
  19939. return;
  19940. }
  19941. this._applyFog = value;
  19942. this._markSubMeshesAsMiscDirty();
  19943. },
  19944. enumerable: true,
  19945. configurable: true
  19946. });
  19947. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19948. /**
  19949. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19950. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19951. */
  19952. get: function () {
  19953. return this._layerMask;
  19954. },
  19955. set: function (value) {
  19956. if (value === this._layerMask) {
  19957. return;
  19958. }
  19959. this._layerMask = value;
  19960. this._resyncLightSources();
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19966. /**
  19967. * Gets or sets a collision mask used to mask collisions (default is -1).
  19968. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19969. */
  19970. get: function () {
  19971. return this._collisionMask;
  19972. },
  19973. set: function (mask) {
  19974. this._collisionMask = !isNaN(mask) ? mask : -1;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19980. /**
  19981. * Gets or sets the current collision group mask (-1 by default).
  19982. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19983. */
  19984. get: function () {
  19985. return this._collisionGroup;
  19986. },
  19987. set: function (mask) {
  19988. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19994. /** @hidden */
  19995. get: function () {
  19996. return null;
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20002. get: function () {
  20003. return this._skeleton;
  20004. },
  20005. /**
  20006. * Gets or sets a skeleton to apply skining transformations
  20007. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20008. */
  20009. set: function (value) {
  20010. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20011. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20012. }
  20013. if (value && value.needInitialSkinMatrix) {
  20014. value._registerMeshWithPoseMatrix(this);
  20015. }
  20016. this._skeleton = value;
  20017. if (!this._skeleton) {
  20018. this._bonesTransformMatrices = null;
  20019. }
  20020. this._markSubMeshesAsAttributesDirty();
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. /**
  20026. * Returns the string "AbstractMesh"
  20027. * @returns "AbstractMesh"
  20028. */
  20029. AbstractMesh.prototype.getClassName = function () {
  20030. return "AbstractMesh";
  20031. };
  20032. /**
  20033. * Gets a string representation of the current mesh
  20034. * @param fullDetails defines a boolean indicating if full details must be included
  20035. * @returns a string representation of the current mesh
  20036. */
  20037. AbstractMesh.prototype.toString = function (fullDetails) {
  20038. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20039. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20040. if (this._skeleton) {
  20041. ret += ", skeleton: " + this._skeleton.name;
  20042. }
  20043. if (fullDetails) {
  20044. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20045. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20046. }
  20047. return ret;
  20048. };
  20049. /** @hidden */
  20050. AbstractMesh.prototype._rebuild = function () {
  20051. if (this._occlusionQuery) {
  20052. this._occlusionQuery = null;
  20053. }
  20054. if (this._edgesRenderer) {
  20055. this._edgesRenderer._rebuild();
  20056. }
  20057. if (!this.subMeshes) {
  20058. return;
  20059. }
  20060. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20061. var subMesh = _a[_i];
  20062. subMesh._rebuild();
  20063. }
  20064. };
  20065. /** @hidden */
  20066. AbstractMesh.prototype._resyncLightSources = function () {
  20067. this._lightSources.length = 0;
  20068. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20069. var light = _a[_i];
  20070. if (!light.isEnabled()) {
  20071. continue;
  20072. }
  20073. if (light.canAffectMesh(this)) {
  20074. this._lightSources.push(light);
  20075. }
  20076. }
  20077. this._markSubMeshesAsLightDirty();
  20078. };
  20079. /** @hidden */
  20080. AbstractMesh.prototype._resyncLighSource = function (light) {
  20081. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20082. var index = this._lightSources.indexOf(light);
  20083. if (index === -1) {
  20084. if (!isIn) {
  20085. return;
  20086. }
  20087. this._lightSources.push(light);
  20088. }
  20089. else {
  20090. if (isIn) {
  20091. return;
  20092. }
  20093. this._lightSources.splice(index, 1);
  20094. }
  20095. this._markSubMeshesAsLightDirty();
  20096. };
  20097. /** @hidden */
  20098. AbstractMesh.prototype._unBindEffect = function () {
  20099. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20100. var subMesh = _a[_i];
  20101. subMesh.setEffect(null);
  20102. }
  20103. };
  20104. /** @hidden */
  20105. AbstractMesh.prototype._removeLightSource = function (light) {
  20106. var index = this._lightSources.indexOf(light);
  20107. if (index === -1) {
  20108. return;
  20109. }
  20110. this._lightSources.splice(index, 1);
  20111. this._markSubMeshesAsLightDirty();
  20112. };
  20113. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20114. if (!this.subMeshes) {
  20115. return;
  20116. }
  20117. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20118. var subMesh = _a[_i];
  20119. if (subMesh._materialDefines) {
  20120. func(subMesh._materialDefines);
  20121. }
  20122. }
  20123. };
  20124. /** @hidden */
  20125. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20126. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20127. };
  20128. /** @hidden */
  20129. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20130. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20131. };
  20132. /** @hidden */
  20133. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20134. if (!this.subMeshes) {
  20135. return;
  20136. }
  20137. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20138. var subMesh = _a[_i];
  20139. var material = subMesh.getMaterial();
  20140. if (material) {
  20141. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20142. }
  20143. }
  20144. };
  20145. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20146. /**
  20147. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20148. */
  20149. get: function () {
  20150. return this._scaling;
  20151. },
  20152. set: function (newScaling) {
  20153. this._scaling = newScaling;
  20154. if (this.physicsImpostor) {
  20155. this.physicsImpostor.forceUpdate();
  20156. }
  20157. },
  20158. enumerable: true,
  20159. configurable: true
  20160. });
  20161. // Methods
  20162. /**
  20163. * Disables the mesh edge rendering mode
  20164. * @returns the currentAbstractMesh
  20165. */
  20166. AbstractMesh.prototype.disableEdgesRendering = function () {
  20167. if (this._edgesRenderer) {
  20168. this._edgesRenderer.dispose();
  20169. this._edgesRenderer = null;
  20170. }
  20171. return this;
  20172. };
  20173. /**
  20174. * Enables the edge rendering mode on the mesh.
  20175. * This mode makes the mesh edges visible
  20176. * @param epsilon defines the maximal distance between two angles to detect a face
  20177. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20178. * @returns the currentAbstractMesh
  20179. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20180. */
  20181. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20182. if (epsilon === void 0) { epsilon = 0.95; }
  20183. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20184. this.disableEdgesRendering();
  20185. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20186. return this;
  20187. };
  20188. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20189. /**
  20190. * Gets the edgesRenderer associated with the mesh
  20191. */
  20192. get: function () {
  20193. return this._edgesRenderer;
  20194. },
  20195. enumerable: true,
  20196. configurable: true
  20197. });
  20198. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20199. /**
  20200. * Returns true if the mesh is blocked. Implemented by child classes
  20201. */
  20202. get: function () {
  20203. return false;
  20204. },
  20205. enumerable: true,
  20206. configurable: true
  20207. });
  20208. /**
  20209. * Returns the mesh itself by default. Implemented by child classes
  20210. * @param camera defines the camera to use to pick the right LOD level
  20211. * @returns the currentAbstractMesh
  20212. */
  20213. AbstractMesh.prototype.getLOD = function (camera) {
  20214. return this;
  20215. };
  20216. /**
  20217. * Returns 0 by default. Implemented by child classes
  20218. * @returns an integer
  20219. */
  20220. AbstractMesh.prototype.getTotalVertices = function () {
  20221. return 0;
  20222. };
  20223. /**
  20224. * Returns null by default. Implemented by child classes
  20225. * @returns null
  20226. */
  20227. AbstractMesh.prototype.getIndices = function () {
  20228. return null;
  20229. };
  20230. /**
  20231. * Returns the array of the requested vertex data kind. Implemented by child classes
  20232. * @param kind defines the vertex data kind to use
  20233. * @returns null
  20234. */
  20235. AbstractMesh.prototype.getVerticesData = function (kind) {
  20236. return null;
  20237. };
  20238. /**
  20239. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20240. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20241. * Note that a new underlying VertexBuffer object is created each call.
  20242. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20243. * @param kind defines vertex data kind:
  20244. * * BABYLON.VertexBuffer.PositionKind
  20245. * * BABYLON.VertexBuffer.UVKind
  20246. * * BABYLON.VertexBuffer.UV2Kind
  20247. * * BABYLON.VertexBuffer.UV3Kind
  20248. * * BABYLON.VertexBuffer.UV4Kind
  20249. * * BABYLON.VertexBuffer.UV5Kind
  20250. * * BABYLON.VertexBuffer.UV6Kind
  20251. * * BABYLON.VertexBuffer.ColorKind
  20252. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20253. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20254. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20255. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20256. * @param data defines the data source
  20257. * @param updatable defines if the data must be flagged as updatable (or static)
  20258. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20259. * @returns the current mesh
  20260. */
  20261. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20262. return this;
  20263. };
  20264. /**
  20265. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20266. * If the mesh has no geometry, it is simply returned as it is.
  20267. * @param kind defines vertex data kind:
  20268. * * BABYLON.VertexBuffer.PositionKind
  20269. * * BABYLON.VertexBuffer.UVKind
  20270. * * BABYLON.VertexBuffer.UV2Kind
  20271. * * BABYLON.VertexBuffer.UV3Kind
  20272. * * BABYLON.VertexBuffer.UV4Kind
  20273. * * BABYLON.VertexBuffer.UV5Kind
  20274. * * BABYLON.VertexBuffer.UV6Kind
  20275. * * BABYLON.VertexBuffer.ColorKind
  20276. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20277. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20278. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20279. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20280. * @param data defines the data source
  20281. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20282. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20283. * @returns the current mesh
  20284. */
  20285. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20286. return this;
  20287. };
  20288. /**
  20289. * Sets the mesh indices,
  20290. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20291. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20292. * @param totalVertices Defines the total number of vertices
  20293. * @returns the current mesh
  20294. */
  20295. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20296. return this;
  20297. };
  20298. /**
  20299. * Gets a boolean indicating if specific vertex data is present
  20300. * @param kind defines the vertex data kind to use
  20301. * @returns true is data kind is present
  20302. */
  20303. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20304. return false;
  20305. };
  20306. /**
  20307. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20308. * @returns a BoundingInfo
  20309. */
  20310. AbstractMesh.prototype.getBoundingInfo = function () {
  20311. if (this._masterMesh) {
  20312. return this._masterMesh.getBoundingInfo();
  20313. }
  20314. if (!this._boundingInfo) {
  20315. // this._boundingInfo is being created here
  20316. this._updateBoundingInfo();
  20317. }
  20318. // cannot be null.
  20319. return this._boundingInfo;
  20320. };
  20321. /**
  20322. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20323. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20324. * @returns the current mesh
  20325. */
  20326. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20327. if (includeDescendants === void 0) { includeDescendants = true; }
  20328. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20329. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20330. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20331. if (maxDimension === 0) {
  20332. return this;
  20333. }
  20334. var scale = 1 / maxDimension;
  20335. this.scaling.scaleInPlace(scale);
  20336. return this;
  20337. };
  20338. /**
  20339. * Overwrite the current bounding info
  20340. * @param boundingInfo defines the new bounding info
  20341. * @returns the current mesh
  20342. */
  20343. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20344. this._boundingInfo = boundingInfo;
  20345. return this;
  20346. };
  20347. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20348. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20349. get: function () {
  20350. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20351. },
  20352. enumerable: true,
  20353. configurable: true
  20354. });
  20355. /** @hidden */
  20356. AbstractMesh.prototype._preActivate = function () {
  20357. };
  20358. /** @hidden */
  20359. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20360. };
  20361. /** @hidden */
  20362. AbstractMesh.prototype._activate = function (renderId) {
  20363. this._renderId = renderId;
  20364. };
  20365. /**
  20366. * Gets the current world matrix
  20367. * @returns a Matrix
  20368. */
  20369. AbstractMesh.prototype.getWorldMatrix = function () {
  20370. if (this._masterMesh) {
  20371. return this._masterMesh.getWorldMatrix();
  20372. }
  20373. return _super.prototype.getWorldMatrix.call(this);
  20374. };
  20375. /** @hidden */
  20376. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20377. if (this._masterMesh) {
  20378. return this._masterMesh._getWorldMatrixDeterminant();
  20379. }
  20380. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20381. };
  20382. // ================================== Point of View Movement =================================
  20383. /**
  20384. * Perform relative position change from the point of view of behind the front of the mesh.
  20385. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20386. * Supports definition of mesh facing forward or backward
  20387. * @param amountRight defines the distance on the right axis
  20388. * @param amountUp defines the distance on the up axis
  20389. * @param amountForward defines the distance on the forward axis
  20390. * @returns the current mesh
  20391. */
  20392. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20393. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20394. return this;
  20395. };
  20396. /**
  20397. * Calculate relative position change from the point of view of behind the front of the mesh.
  20398. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20399. * Supports definition of mesh facing forward or backward
  20400. * @param amountRight defines the distance on the right axis
  20401. * @param amountUp defines the distance on the up axis
  20402. * @param amountForward defines the distance on the forward axis
  20403. * @returns the new displacement vector
  20404. */
  20405. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20406. var rotMatrix = new BABYLON.Matrix();
  20407. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20408. rotQuaternion.toRotationMatrix(rotMatrix);
  20409. var translationDelta = BABYLON.Vector3.Zero();
  20410. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20411. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20412. return translationDelta;
  20413. };
  20414. // ================================== Point of View Rotation =================================
  20415. /**
  20416. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20417. * Supports definition of mesh facing forward or backward
  20418. * @param flipBack defines the flip
  20419. * @param twirlClockwise defines the twirl
  20420. * @param tiltRight defines the tilt
  20421. * @returns the current mesh
  20422. */
  20423. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20424. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20425. return this;
  20426. };
  20427. /**
  20428. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20429. * Supports definition of mesh facing forward or backward.
  20430. * @param flipBack defines the flip
  20431. * @param twirlClockwise defines the twirl
  20432. * @param tiltRight defines the tilt
  20433. * @returns the new rotation vector
  20434. */
  20435. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20436. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20437. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20438. };
  20439. /**
  20440. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20441. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20442. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20443. * @returns the new bounding vectors
  20444. */
  20445. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20446. if (includeDescendants === void 0) { includeDescendants = true; }
  20447. if (predicate === void 0) { predicate = null; }
  20448. // Ensures that all world matrix will be recomputed.
  20449. this.getScene().incrementRenderId();
  20450. this.computeWorldMatrix(true);
  20451. var min;
  20452. var max;
  20453. var boundingInfo = this.getBoundingInfo();
  20454. if (!this.subMeshes) {
  20455. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20456. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20457. }
  20458. else {
  20459. min = boundingInfo.boundingBox.minimumWorld;
  20460. max = boundingInfo.boundingBox.maximumWorld;
  20461. }
  20462. if (includeDescendants) {
  20463. var descendants = this.getDescendants(false);
  20464. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20465. var descendant = descendants_1[_i];
  20466. var childMesh = descendant;
  20467. childMesh.computeWorldMatrix(true);
  20468. // Filters meshes based on custom predicate function.
  20469. if (predicate && !predicate(childMesh)) {
  20470. continue;
  20471. }
  20472. //make sure we have the needed params to get mix and max
  20473. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20474. continue;
  20475. }
  20476. var childBoundingInfo = childMesh.getBoundingInfo();
  20477. var boundingBox = childBoundingInfo.boundingBox;
  20478. var minBox = boundingBox.minimumWorld;
  20479. var maxBox = boundingBox.maximumWorld;
  20480. BABYLON.Tools.CheckExtends(minBox, min, max);
  20481. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20482. }
  20483. }
  20484. return {
  20485. min: min,
  20486. max: max
  20487. };
  20488. };
  20489. /** @hidden */
  20490. AbstractMesh.prototype._updateBoundingInfo = function () {
  20491. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20492. this._boundingInfo.update(this.worldMatrixFromCache);
  20493. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20494. return this;
  20495. };
  20496. /** @hidden */
  20497. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20498. if (!this.subMeshes) {
  20499. return this;
  20500. }
  20501. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20502. var subMesh = this.subMeshes[subIndex];
  20503. if (!subMesh.IsGlobal) {
  20504. subMesh.updateBoundingInfo(matrix);
  20505. }
  20506. }
  20507. return this;
  20508. };
  20509. /** @hidden */
  20510. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20511. // Bounding info
  20512. this._updateBoundingInfo();
  20513. };
  20514. /**
  20515. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20516. * A mesh is in the frustum if its bounding box intersects the frustum
  20517. * @param frustumPlanes defines the frustum to test
  20518. * @returns true if the mesh is in the frustum planes
  20519. */
  20520. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20521. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20522. };
  20523. /**
  20524. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20525. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20526. * @param frustumPlanes defines the frustum to test
  20527. * @returns true if the mesh is completely in the frustum planes
  20528. */
  20529. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20530. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20531. };
  20532. /**
  20533. * True if the mesh intersects another mesh or a SolidParticle object
  20534. * @param mesh defines a target mesh or SolidParticle to test
  20535. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20536. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20537. * @returns true if there is an intersection
  20538. */
  20539. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20540. if (precise === void 0) { precise = false; }
  20541. if (!this._boundingInfo || !mesh._boundingInfo) {
  20542. return false;
  20543. }
  20544. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20545. return true;
  20546. }
  20547. if (includeDescendants) {
  20548. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20549. var child = _a[_i];
  20550. if (child.intersectsMesh(mesh, precise, true)) {
  20551. return true;
  20552. }
  20553. }
  20554. }
  20555. return false;
  20556. };
  20557. /**
  20558. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20559. * @param point defines the point to test
  20560. * @returns true if there is an intersection
  20561. */
  20562. AbstractMesh.prototype.intersectsPoint = function (point) {
  20563. if (!this._boundingInfo) {
  20564. return false;
  20565. }
  20566. return this._boundingInfo.intersectsPoint(point);
  20567. };
  20568. /**
  20569. * Gets the current physics impostor
  20570. * @see http://doc.babylonjs.com/features/physics_engine
  20571. * @returns a physics impostor or null
  20572. */
  20573. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20574. return this.physicsImpostor;
  20575. };
  20576. /**
  20577. * Gets the position of the current mesh in camera space
  20578. * @param camera defines the camera to use
  20579. * @returns a position
  20580. */
  20581. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20582. if (camera === void 0) { camera = null; }
  20583. if (!camera) {
  20584. camera = this.getScene().activeCamera;
  20585. }
  20586. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20587. };
  20588. /**
  20589. * Returns the distance from the mesh to the active camera
  20590. * @param camera defines the camera to use
  20591. * @returns the distance
  20592. */
  20593. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20594. if (camera === void 0) { camera = null; }
  20595. if (!camera) {
  20596. camera = this.getScene().activeCamera;
  20597. }
  20598. return this.absolutePosition.subtract(camera.position).length();
  20599. };
  20600. /**
  20601. * Apply a physic impulse to the mesh
  20602. * @param force defines the force to apply
  20603. * @param contactPoint defines where to apply the force
  20604. * @returns the current mesh
  20605. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20606. */
  20607. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20608. if (!this.physicsImpostor) {
  20609. return this;
  20610. }
  20611. this.physicsImpostor.applyImpulse(force, contactPoint);
  20612. return this;
  20613. };
  20614. /**
  20615. * Creates a physic joint between two meshes
  20616. * @param otherMesh defines the other mesh to use
  20617. * @param pivot1 defines the pivot to use on this mesh
  20618. * @param pivot2 defines the pivot to use on the other mesh
  20619. * @param options defines additional options (can be plugin dependent)
  20620. * @returns the current mesh
  20621. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20622. */
  20623. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20624. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20625. return this;
  20626. }
  20627. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20628. mainPivot: pivot1,
  20629. connectedPivot: pivot2,
  20630. nativeParams: options
  20631. });
  20632. return this;
  20633. };
  20634. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20635. // Collisions
  20636. /**
  20637. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20638. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20639. */
  20640. get: function () {
  20641. return this._checkCollisions;
  20642. },
  20643. set: function (collisionEnabled) {
  20644. this._checkCollisions = collisionEnabled;
  20645. if (this.getScene().workerCollisions) {
  20646. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20647. }
  20648. },
  20649. enumerable: true,
  20650. configurable: true
  20651. });
  20652. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20653. /**
  20654. * Gets Collider object used to compute collisions (not physics)
  20655. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20656. */
  20657. get: function () {
  20658. return this._collider;
  20659. },
  20660. enumerable: true,
  20661. configurable: true
  20662. });
  20663. /**
  20664. * Move the mesh using collision engine
  20665. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20666. * @param displacement defines the requested displacement vector
  20667. * @returns the current mesh
  20668. */
  20669. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20670. var globalPosition = this.getAbsolutePosition();
  20671. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20672. if (!this._collider) {
  20673. this._collider = new BABYLON.Collider();
  20674. }
  20675. this._collider._radius = this.ellipsoid;
  20676. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20677. return this;
  20678. };
  20679. // Submeshes octree
  20680. /**
  20681. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20682. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20683. * @param maxCapacity defines the maximum size of each block (64 by default)
  20684. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20685. * @returns the new octree
  20686. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20687. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20688. */
  20689. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20690. if (maxCapacity === void 0) { maxCapacity = 64; }
  20691. if (maxDepth === void 0) { maxDepth = 2; }
  20692. if (!this._submeshesOctree) {
  20693. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20694. }
  20695. this.computeWorldMatrix(true);
  20696. var boundingInfo = this.getBoundingInfo();
  20697. // Update octree
  20698. var bbox = boundingInfo.boundingBox;
  20699. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20700. return this._submeshesOctree;
  20701. };
  20702. // Collisions
  20703. /** @hidden */
  20704. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20705. this._generatePointsArray();
  20706. if (!this._positions) {
  20707. return this;
  20708. }
  20709. // Transformation
  20710. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20711. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20712. subMesh._lastColliderWorldVertices = [];
  20713. subMesh._trianglePlanes = [];
  20714. var start = subMesh.verticesStart;
  20715. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20716. for (var i = start; i < end; i++) {
  20717. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20718. }
  20719. }
  20720. // Collide
  20721. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20722. if (collider.collisionFound) {
  20723. collider.collidedMesh = this;
  20724. }
  20725. return this;
  20726. };
  20727. /** @hidden */
  20728. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20729. var subMeshes;
  20730. var len;
  20731. // Octrees
  20732. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20733. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20734. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20735. len = intersections.length;
  20736. subMeshes = intersections.data;
  20737. }
  20738. else {
  20739. subMeshes = this.subMeshes;
  20740. len = subMeshes.length;
  20741. }
  20742. for (var index = 0; index < len; index++) {
  20743. var subMesh = subMeshes[index];
  20744. // Bounding test
  20745. if (len > 1 && !subMesh._checkCollision(collider))
  20746. continue;
  20747. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20748. }
  20749. return this;
  20750. };
  20751. /** @hidden */
  20752. AbstractMesh.prototype._checkCollision = function (collider) {
  20753. // Bounding box test
  20754. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20755. return this;
  20756. // Transformation matrix
  20757. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20758. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20759. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20760. return this;
  20761. };
  20762. // Picking
  20763. /** @hidden */
  20764. AbstractMesh.prototype._generatePointsArray = function () {
  20765. return false;
  20766. };
  20767. /**
  20768. * Checks if the passed Ray intersects with the mesh
  20769. * @param ray defines the ray to use
  20770. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20771. * @returns the picking info
  20772. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20773. */
  20774. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20775. var pickingInfo = new BABYLON.PickingInfo();
  20776. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20777. return pickingInfo;
  20778. }
  20779. if (!this._generatePointsArray()) {
  20780. return pickingInfo;
  20781. }
  20782. var intersectInfo = null;
  20783. // Octrees
  20784. var subMeshes;
  20785. var len;
  20786. if (this._submeshesOctree && this.useOctreeForPicking) {
  20787. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20788. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20789. len = intersections.length;
  20790. subMeshes = intersections.data;
  20791. }
  20792. else {
  20793. subMeshes = this.subMeshes;
  20794. len = subMeshes.length;
  20795. }
  20796. for (var index = 0; index < len; index++) {
  20797. var subMesh = subMeshes[index];
  20798. // Bounding test
  20799. if (len > 1 && !subMesh.canIntersects(ray))
  20800. continue;
  20801. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20802. if (currentIntersectInfo) {
  20803. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20804. intersectInfo = currentIntersectInfo;
  20805. intersectInfo.subMeshId = index;
  20806. if (fastCheck) {
  20807. break;
  20808. }
  20809. }
  20810. }
  20811. }
  20812. if (intersectInfo) {
  20813. // Get picked point
  20814. var world = this.getWorldMatrix();
  20815. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20816. var direction = ray.direction.clone();
  20817. direction = direction.scale(intersectInfo.distance);
  20818. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20819. var pickedPoint = worldOrigin.add(worldDirection);
  20820. // Return result
  20821. pickingInfo.hit = true;
  20822. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20823. pickingInfo.pickedPoint = pickedPoint;
  20824. pickingInfo.pickedMesh = this;
  20825. pickingInfo.bu = intersectInfo.bu || 0;
  20826. pickingInfo.bv = intersectInfo.bv || 0;
  20827. pickingInfo.faceId = intersectInfo.faceId;
  20828. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20829. return pickingInfo;
  20830. }
  20831. return pickingInfo;
  20832. };
  20833. /**
  20834. * Clones the current mesh
  20835. * @param name defines the mesh name
  20836. * @param newParent defines the new mesh parent
  20837. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20838. * @returns the new mesh
  20839. */
  20840. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20841. return null;
  20842. };
  20843. /**
  20844. * Disposes all the submeshes of the current meshnp
  20845. * @returns the current mesh
  20846. */
  20847. AbstractMesh.prototype.releaseSubMeshes = function () {
  20848. if (this.subMeshes) {
  20849. while (this.subMeshes.length) {
  20850. this.subMeshes[0].dispose();
  20851. }
  20852. }
  20853. else {
  20854. this.subMeshes = new Array();
  20855. }
  20856. return this;
  20857. };
  20858. /**
  20859. * Releases resources associated with this abstract mesh.
  20860. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20861. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20862. */
  20863. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20864. var _this = this;
  20865. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20866. var index;
  20867. // Smart Array Retainers.
  20868. this.getScene().freeActiveMeshes();
  20869. this.getScene().freeRenderingGroups();
  20870. // Action manager
  20871. if (this.actionManager !== undefined && this.actionManager !== null) {
  20872. this.actionManager.dispose();
  20873. this.actionManager = null;
  20874. }
  20875. // Skeleton
  20876. this._skeleton = null;
  20877. // Physics
  20878. if (this.physicsImpostor) {
  20879. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20880. }
  20881. // Intersections in progress
  20882. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20883. var other = this._intersectionsInProgress[index];
  20884. var pos = other._intersectionsInProgress.indexOf(this);
  20885. other._intersectionsInProgress.splice(pos, 1);
  20886. }
  20887. this._intersectionsInProgress = [];
  20888. // Lights
  20889. var lights = this.getScene().lights;
  20890. lights.forEach(function (light) {
  20891. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20892. if (meshIndex !== -1) {
  20893. light.includedOnlyMeshes.splice(meshIndex, 1);
  20894. }
  20895. meshIndex = light.excludedMeshes.indexOf(_this);
  20896. if (meshIndex !== -1) {
  20897. light.excludedMeshes.splice(meshIndex, 1);
  20898. }
  20899. // Shadow generators
  20900. var generator = light.getShadowGenerator();
  20901. if (generator) {
  20902. var shadowMap = generator.getShadowMap();
  20903. if (shadowMap && shadowMap.renderList) {
  20904. meshIndex = shadowMap.renderList.indexOf(_this);
  20905. if (meshIndex !== -1) {
  20906. shadowMap.renderList.splice(meshIndex, 1);
  20907. }
  20908. }
  20909. }
  20910. });
  20911. // Edges
  20912. if (this._edgesRenderer) {
  20913. this._edgesRenderer.dispose();
  20914. this._edgesRenderer = null;
  20915. }
  20916. // SubMeshes
  20917. if (this.getClassName() !== "InstancedMesh") {
  20918. this.releaseSubMeshes();
  20919. }
  20920. // Octree
  20921. var sceneOctree = this.getScene().selectionOctree;
  20922. if (sceneOctree !== undefined && sceneOctree !== null) {
  20923. var index = sceneOctree.dynamicContent.indexOf(this);
  20924. if (index !== -1) {
  20925. sceneOctree.dynamicContent.splice(index, 1);
  20926. }
  20927. }
  20928. // Query
  20929. var engine = this.getScene().getEngine();
  20930. if (this._occlusionQuery) {
  20931. this._isOcclusionQueryInProgress = false;
  20932. engine.deleteQuery(this._occlusionQuery);
  20933. this._occlusionQuery = null;
  20934. }
  20935. // Engine
  20936. engine.wipeCaches();
  20937. // Remove from scene
  20938. this.getScene().removeMesh(this);
  20939. if (disposeMaterialAndTextures) {
  20940. if (this.material) {
  20941. this.material.dispose(false, true);
  20942. }
  20943. }
  20944. if (!doNotRecurse) {
  20945. // Particles
  20946. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20947. if (this.getScene().particleSystems[index].emitter === this) {
  20948. this.getScene().particleSystems[index].dispose();
  20949. index--;
  20950. }
  20951. }
  20952. }
  20953. // facet data
  20954. if (this._facetDataEnabled) {
  20955. this.disableFacetData();
  20956. }
  20957. this.onAfterWorldMatrixUpdateObservable.clear();
  20958. this.onCollideObservable.clear();
  20959. this.onCollisionPositionChangeObservable.clear();
  20960. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20961. };
  20962. /**
  20963. * Adds the passed mesh as a child to the current mesh
  20964. * @param mesh defines the child mesh
  20965. * @returns the current mesh
  20966. */
  20967. AbstractMesh.prototype.addChild = function (mesh) {
  20968. mesh.setParent(this);
  20969. return this;
  20970. };
  20971. /**
  20972. * Removes the passed mesh from the current mesh children list
  20973. * @param mesh defines the child mesh
  20974. * @returns the current mesh
  20975. */
  20976. AbstractMesh.prototype.removeChild = function (mesh) {
  20977. mesh.setParent(null);
  20978. return this;
  20979. };
  20980. // Facet data
  20981. /** @hidden */
  20982. AbstractMesh.prototype._initFacetData = function () {
  20983. if (!this._facetNormals) {
  20984. this._facetNormals = new Array();
  20985. }
  20986. if (!this._facetPositions) {
  20987. this._facetPositions = new Array();
  20988. }
  20989. if (!this._facetPartitioning) {
  20990. this._facetPartitioning = new Array();
  20991. }
  20992. this._facetNb = (this.getIndices().length / 3) | 0;
  20993. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20994. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20995. for (var f = 0; f < this._facetNb; f++) {
  20996. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20997. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20998. }
  20999. this._facetDataEnabled = true;
  21000. return this;
  21001. };
  21002. /**
  21003. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21004. * This method can be called within the render loop.
  21005. * 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
  21006. * @returns the current mesh
  21007. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21008. */
  21009. AbstractMesh.prototype.updateFacetData = function () {
  21010. if (!this._facetDataEnabled) {
  21011. this._initFacetData();
  21012. }
  21013. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21014. var indices = this.getIndices();
  21015. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21016. var bInfo = this.getBoundingInfo();
  21017. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21018. // init arrays, matrix and sort function on first call
  21019. this._facetDepthSortEnabled = true;
  21020. if (indices instanceof Uint16Array) {
  21021. this._depthSortedIndices = new Uint16Array(indices);
  21022. }
  21023. else if (indices instanceof Uint32Array) {
  21024. this._depthSortedIndices = new Uint32Array(indices);
  21025. }
  21026. else {
  21027. var needs32bits = false;
  21028. for (var i = 0; i < indices.length; i++) {
  21029. if (indices[i] > 65535) {
  21030. needs32bits = true;
  21031. break;
  21032. }
  21033. }
  21034. if (needs32bits) {
  21035. this._depthSortedIndices = new Uint32Array(indices);
  21036. }
  21037. else {
  21038. this._depthSortedIndices = new Uint16Array(indices);
  21039. }
  21040. }
  21041. this._facetDepthSortFunction = function (f1, f2) {
  21042. return (f2.sqDistance - f1.sqDistance);
  21043. };
  21044. if (!this._facetDepthSortFrom) {
  21045. var camera = this.getScene().activeCamera;
  21046. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21047. }
  21048. this._depthSortedFacets = [];
  21049. for (var f = 0; f < this._facetNb; f++) {
  21050. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21051. this._depthSortedFacets.push(depthSortedFacet);
  21052. }
  21053. this._invertedMatrix = BABYLON.Matrix.Identity();
  21054. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21055. }
  21056. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21057. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21058. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21059. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21060. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21061. this._subDiv.max = this._partitioningSubdivisions;
  21062. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21063. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21064. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21065. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21066. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21067. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21068. // set the parameters for ComputeNormals()
  21069. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21070. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21071. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21072. this._facetParameters.bInfo = bInfo;
  21073. this._facetParameters.bbSize = this._bbSize;
  21074. this._facetParameters.subDiv = this._subDiv;
  21075. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21076. this._facetParameters.depthSort = this._facetDepthSort;
  21077. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21078. this.computeWorldMatrix(true);
  21079. this._worldMatrix.invertToRef(this._invertedMatrix);
  21080. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21081. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21082. }
  21083. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21084. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21085. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21086. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21087. var l = (this._depthSortedIndices.length / 3) | 0;
  21088. for (var f = 0; f < l; f++) {
  21089. var sind = this._depthSortedFacets[f].ind;
  21090. this._depthSortedIndices[f * 3] = indices[sind];
  21091. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21092. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21093. }
  21094. this.updateIndices(this._depthSortedIndices);
  21095. }
  21096. return this;
  21097. };
  21098. /**
  21099. * Returns the facetLocalNormals array.
  21100. * The normals are expressed in the mesh local spac
  21101. * @returns an array of Vector3
  21102. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21103. */
  21104. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21105. if (!this._facetNormals) {
  21106. this.updateFacetData();
  21107. }
  21108. return this._facetNormals;
  21109. };
  21110. /**
  21111. * Returns the facetLocalPositions array.
  21112. * The facet positions are expressed in the mesh local space
  21113. * @returns an array of Vector3
  21114. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21115. */
  21116. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21117. if (!this._facetPositions) {
  21118. this.updateFacetData();
  21119. }
  21120. return this._facetPositions;
  21121. };
  21122. /**
  21123. * Returns the facetLocalPartioning array
  21124. * @returns an array of array of numbers
  21125. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21126. */
  21127. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21128. if (!this._facetPartitioning) {
  21129. this.updateFacetData();
  21130. }
  21131. return this._facetPartitioning;
  21132. };
  21133. /**
  21134. * Returns the i-th facet position in the world system.
  21135. * This method allocates a new Vector3 per call
  21136. * @param i defines the facet index
  21137. * @returns a new Vector3
  21138. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21139. */
  21140. AbstractMesh.prototype.getFacetPosition = function (i) {
  21141. var pos = BABYLON.Vector3.Zero();
  21142. this.getFacetPositionToRef(i, pos);
  21143. return pos;
  21144. };
  21145. /**
  21146. * Sets the reference Vector3 with the i-th facet position in the world system
  21147. * @param i defines the facet index
  21148. * @param ref defines the target vector
  21149. * @returns the current mesh
  21150. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21151. */
  21152. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21153. var localPos = (this.getFacetLocalPositions())[i];
  21154. var world = this.getWorldMatrix();
  21155. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21156. return this;
  21157. };
  21158. /**
  21159. * Returns the i-th facet normal in the world system.
  21160. * This method allocates a new Vector3 per call
  21161. * @param i defines the facet index
  21162. * @returns a new Vector3
  21163. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21164. */
  21165. AbstractMesh.prototype.getFacetNormal = function (i) {
  21166. var norm = BABYLON.Vector3.Zero();
  21167. this.getFacetNormalToRef(i, norm);
  21168. return norm;
  21169. };
  21170. /**
  21171. * Sets the reference Vector3 with the i-th facet normal in the world system
  21172. * @param i defines the facet index
  21173. * @param ref defines the target vector
  21174. * @returns the current mesh
  21175. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21176. */
  21177. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21178. var localNorm = (this.getFacetLocalNormals())[i];
  21179. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21180. return this;
  21181. };
  21182. /**
  21183. * 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)
  21184. * @param x defines x coordinate
  21185. * @param y defines y coordinate
  21186. * @param z defines z coordinate
  21187. * @returns the array of facet indexes
  21188. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21189. */
  21190. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21191. var bInfo = this.getBoundingInfo();
  21192. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21193. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21194. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21195. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21196. return null;
  21197. }
  21198. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21199. };
  21200. /**
  21201. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21202. * @param projected sets as the (x,y,z) world projection on the facet
  21203. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21204. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21205. * @param x defines x coordinate
  21206. * @param y defines y coordinate
  21207. * @param z defines z coordinate
  21208. * @returns the face index if found (or null instead)
  21209. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21210. */
  21211. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21212. if (checkFace === void 0) { checkFace = false; }
  21213. if (facing === void 0) { facing = true; }
  21214. var world = this.getWorldMatrix();
  21215. var invMat = BABYLON.Tmp.Matrix[5];
  21216. world.invertToRef(invMat);
  21217. var invVect = BABYLON.Tmp.Vector3[8];
  21218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21219. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21220. if (projected) {
  21221. // tranform the local computed projected vector to world coordinates
  21222. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21223. }
  21224. return closest;
  21225. };
  21226. /**
  21227. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21228. * @param projected sets as the (x,y,z) local projection on the facet
  21229. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21230. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21231. * @param x defines x coordinate
  21232. * @param y defines y coordinate
  21233. * @param z defines z coordinate
  21234. * @returns the face index if found (or null instead)
  21235. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21236. */
  21237. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21238. if (checkFace === void 0) { checkFace = false; }
  21239. if (facing === void 0) { facing = true; }
  21240. var closest = null;
  21241. var tmpx = 0.0;
  21242. var tmpy = 0.0;
  21243. var tmpz = 0.0;
  21244. var d = 0.0; // tmp dot facet normal * facet position
  21245. var t0 = 0.0;
  21246. var projx = 0.0;
  21247. var projy = 0.0;
  21248. var projz = 0.0;
  21249. // Get all the facets in the same partitioning block than (x, y, z)
  21250. var facetPositions = this.getFacetLocalPositions();
  21251. var facetNormals = this.getFacetLocalNormals();
  21252. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21253. if (!facetsInBlock) {
  21254. return null;
  21255. }
  21256. // Get the closest facet to (x, y, z)
  21257. var shortest = Number.MAX_VALUE; // init distance vars
  21258. var tmpDistance = shortest;
  21259. var fib; // current facet in the block
  21260. var norm; // current facet normal
  21261. var p0; // current facet barycenter position
  21262. // loop on all the facets in the current partitioning block
  21263. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21264. fib = facetsInBlock[idx];
  21265. norm = facetNormals[fib];
  21266. p0 = facetPositions[fib];
  21267. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21268. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21269. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21270. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21271. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21272. projx = x + norm.x * t0;
  21273. projy = y + norm.y * t0;
  21274. projz = z + norm.z * t0;
  21275. tmpx = projx - x;
  21276. tmpy = projy - y;
  21277. tmpz = projz - z;
  21278. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21279. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21280. shortest = tmpDistance;
  21281. closest = fib;
  21282. if (projected) {
  21283. projected.x = projx;
  21284. projected.y = projy;
  21285. projected.z = projz;
  21286. }
  21287. }
  21288. }
  21289. }
  21290. return closest;
  21291. };
  21292. /**
  21293. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21294. * @returns the parameters
  21295. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21296. */
  21297. AbstractMesh.prototype.getFacetDataParameters = function () {
  21298. return this._facetParameters;
  21299. };
  21300. /**
  21301. * Disables the feature FacetData and frees the related memory
  21302. * @returns the current mesh
  21303. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21304. */
  21305. AbstractMesh.prototype.disableFacetData = function () {
  21306. if (this._facetDataEnabled) {
  21307. this._facetDataEnabled = false;
  21308. this._facetPositions = new Array();
  21309. this._facetNormals = new Array();
  21310. this._facetPartitioning = new Array();
  21311. this._facetParameters = null;
  21312. this._depthSortedIndices = new Uint32Array(0);
  21313. }
  21314. return this;
  21315. };
  21316. /**
  21317. * Updates the AbstractMesh indices array
  21318. * @param indices defines the data source
  21319. * @returns the current mesh
  21320. */
  21321. AbstractMesh.prototype.updateIndices = function (indices) {
  21322. return this;
  21323. };
  21324. /**
  21325. * Creates new normals data for the mesh
  21326. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21327. * @returns the current mesh
  21328. */
  21329. AbstractMesh.prototype.createNormals = function (updatable) {
  21330. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21331. var indices = this.getIndices();
  21332. var normals;
  21333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21334. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21335. }
  21336. else {
  21337. normals = [];
  21338. }
  21339. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21340. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21341. return this;
  21342. };
  21343. /**
  21344. * Align the mesh with a normal
  21345. * @param normal defines the normal to use
  21346. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21347. * @returns the current mesh
  21348. */
  21349. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21350. if (!upDirection) {
  21351. upDirection = BABYLON.Axis.Y;
  21352. }
  21353. var axisX = BABYLON.Tmp.Vector3[0];
  21354. var axisZ = BABYLON.Tmp.Vector3[1];
  21355. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21356. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21357. if (this.rotationQuaternion) {
  21358. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21359. }
  21360. else {
  21361. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21362. }
  21363. return this;
  21364. };
  21365. /** @hidden */
  21366. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21367. var engine = this.getEngine();
  21368. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21369. this._isOccluded = false;
  21370. return;
  21371. }
  21372. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21373. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21374. if (isOcclusionQueryAvailable) {
  21375. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21376. this._isOcclusionQueryInProgress = false;
  21377. this._occlusionInternalRetryCounter = 0;
  21378. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21379. }
  21380. else {
  21381. this._occlusionInternalRetryCounter++;
  21382. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21383. this._isOcclusionQueryInProgress = false;
  21384. this._occlusionInternalRetryCounter = 0;
  21385. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21386. // if strict continue the last state of the object.
  21387. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21388. }
  21389. else {
  21390. return;
  21391. }
  21392. }
  21393. }
  21394. var scene = this.getScene();
  21395. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21396. if (!this._occlusionQuery) {
  21397. this._occlusionQuery = engine.createQuery();
  21398. }
  21399. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21400. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21401. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21402. this._isOcclusionQueryInProgress = true;
  21403. };
  21404. /** No occlusion */
  21405. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21406. /** Occlusion set to optimisitic */
  21407. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21408. /** Occlusion set to strict */
  21409. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21410. /** Use an accurante occlusion algorithm */
  21411. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21412. /** Use a conservative occlusion algorithm */
  21413. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21414. return AbstractMesh;
  21415. }(BABYLON.TransformNode));
  21416. BABYLON.AbstractMesh = AbstractMesh;
  21417. })(BABYLON || (BABYLON = {}));
  21418. //# sourceMappingURL=babylon.abstractMesh.js.map
  21419. var BABYLON;
  21420. (function (BABYLON) {
  21421. /**
  21422. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21423. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21424. * 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.
  21425. */
  21426. var Light = /** @class */ (function (_super) {
  21427. __extends(Light, _super);
  21428. /**
  21429. * Creates a Light object in the scene.
  21430. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21431. * @param name The firendly name of the light
  21432. * @param scene The scene the light belongs too
  21433. */
  21434. function Light(name, scene) {
  21435. var _this = _super.call(this, name, scene) || this;
  21436. /**
  21437. * Diffuse gives the basic color to an object.
  21438. */
  21439. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21440. /**
  21441. * Specular produces a highlight color on an object.
  21442. * Note: This is note affecting PBR materials.
  21443. */
  21444. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21445. /**
  21446. * Strength of the light.
  21447. * Note: By default it is define in the framework own unit.
  21448. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21449. */
  21450. _this.intensity = 1.0;
  21451. /**
  21452. * Defines how far from the source the light is impacting in scene units.
  21453. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21454. */
  21455. _this.range = Number.MAX_VALUE;
  21456. /**
  21457. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21458. * of light.
  21459. */
  21460. _this._photometricScale = 1.0;
  21461. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21462. _this._radius = 0.00001;
  21463. /**
  21464. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21465. * exceeding the number allowed of the materials.
  21466. */
  21467. _this.renderPriority = 0;
  21468. _this._shadowEnabled = true;
  21469. _this._excludeWithLayerMask = 0;
  21470. _this._includeOnlyWithLayerMask = 0;
  21471. _this._lightmapMode = 0;
  21472. /**
  21473. * @hidden Internal use only.
  21474. */
  21475. _this._excludedMeshesIds = new Array();
  21476. /**
  21477. * @hidden Internal use only.
  21478. */
  21479. _this._includedOnlyMeshesIds = new Array();
  21480. _this.getScene().addLight(_this);
  21481. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21482. _this._buildUniformLayout();
  21483. _this.includedOnlyMeshes = new Array();
  21484. _this.excludedMeshes = new Array();
  21485. _this._resyncMeshes();
  21486. return _this;
  21487. }
  21488. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21489. /**
  21490. * If every light affecting the material is in this lightmapMode,
  21491. * material.lightmapTexture adds or multiplies
  21492. * (depends on material.useLightmapAsShadowmap)
  21493. * after every other light calculations.
  21494. */
  21495. get: function () {
  21496. return Light._LIGHTMAP_DEFAULT;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21502. /**
  21503. * material.lightmapTexture as only diffuse lighting from this light
  21504. * adds only specular lighting from this light
  21505. * adds dynamic shadows
  21506. */
  21507. get: function () {
  21508. return Light._LIGHTMAP_SPECULAR;
  21509. },
  21510. enumerable: true,
  21511. configurable: true
  21512. });
  21513. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21514. /**
  21515. * material.lightmapTexture as only lighting
  21516. * no light calculation from this light
  21517. * only adds dynamic shadows from this light
  21518. */
  21519. get: function () {
  21520. return Light._LIGHTMAP_SHADOWSONLY;
  21521. },
  21522. enumerable: true,
  21523. configurable: true
  21524. });
  21525. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21526. /**
  21527. * Each light type uses the default quantity according to its type:
  21528. * point/spot lights use luminous intensity
  21529. * directional lights use illuminance
  21530. */
  21531. get: function () {
  21532. return Light._INTENSITYMODE_AUTOMATIC;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21538. /**
  21539. * lumen (lm)
  21540. */
  21541. get: function () {
  21542. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21543. },
  21544. enumerable: true,
  21545. configurable: true
  21546. });
  21547. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21548. /**
  21549. * candela (lm/sr)
  21550. */
  21551. get: function () {
  21552. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21558. /**
  21559. * lux (lm/m^2)
  21560. */
  21561. get: function () {
  21562. return Light._INTENSITYMODE_ILLUMINANCE;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21568. /**
  21569. * nit (cd/m^2)
  21570. */
  21571. get: function () {
  21572. return Light._INTENSITYMODE_LUMINANCE;
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21578. /**
  21579. * Light type const id of the point light.
  21580. */
  21581. get: function () {
  21582. return Light._LIGHTTYPEID_POINTLIGHT;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21588. /**
  21589. * Light type const id of the directional light.
  21590. */
  21591. get: function () {
  21592. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21593. },
  21594. enumerable: true,
  21595. configurable: true
  21596. });
  21597. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21598. /**
  21599. * Light type const id of the spot light.
  21600. */
  21601. get: function () {
  21602. return Light._LIGHTTYPEID_SPOTLIGHT;
  21603. },
  21604. enumerable: true,
  21605. configurable: true
  21606. });
  21607. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21608. /**
  21609. * Light type const id of the hemispheric light.
  21610. */
  21611. get: function () {
  21612. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21613. },
  21614. enumerable: true,
  21615. configurable: true
  21616. });
  21617. Object.defineProperty(Light.prototype, "intensityMode", {
  21618. /**
  21619. * Gets the photometric scale used to interpret the intensity.
  21620. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21621. */
  21622. get: function () {
  21623. return this._intensityMode;
  21624. },
  21625. /**
  21626. * Sets the photometric scale used to interpret the intensity.
  21627. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21628. */
  21629. set: function (value) {
  21630. this._intensityMode = value;
  21631. this._computePhotometricScale();
  21632. },
  21633. enumerable: true,
  21634. configurable: true
  21635. });
  21636. ;
  21637. ;
  21638. Object.defineProperty(Light.prototype, "radius", {
  21639. /**
  21640. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21641. */
  21642. get: function () {
  21643. return this._radius;
  21644. },
  21645. /**
  21646. * sets the light radius used by PBR Materials to simulate soft area lights.
  21647. */
  21648. set: function (value) {
  21649. this._radius = value;
  21650. this._computePhotometricScale();
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. ;
  21656. ;
  21657. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21658. /**
  21659. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21660. * the current shadow generator.
  21661. */
  21662. get: function () {
  21663. return this._shadowEnabled;
  21664. },
  21665. /**
  21666. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21667. * the current shadow generator.
  21668. */
  21669. set: function (value) {
  21670. if (this._shadowEnabled === value) {
  21671. return;
  21672. }
  21673. this._shadowEnabled = value;
  21674. this._markMeshesAsLightDirty();
  21675. },
  21676. enumerable: true,
  21677. configurable: true
  21678. });
  21679. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21680. /**
  21681. * Gets the only meshes impacted by this light.
  21682. */
  21683. get: function () {
  21684. return this._includedOnlyMeshes;
  21685. },
  21686. /**
  21687. * Sets the only meshes impacted by this light.
  21688. */
  21689. set: function (value) {
  21690. this._includedOnlyMeshes = value;
  21691. this._hookArrayForIncludedOnly(value);
  21692. },
  21693. enumerable: true,
  21694. configurable: true
  21695. });
  21696. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21697. /**
  21698. * Gets the meshes not impacted by this light.
  21699. */
  21700. get: function () {
  21701. return this._excludedMeshes;
  21702. },
  21703. /**
  21704. * Sets the meshes not impacted by this light.
  21705. */
  21706. set: function (value) {
  21707. this._excludedMeshes = value;
  21708. this._hookArrayForExcluded(value);
  21709. },
  21710. enumerable: true,
  21711. configurable: true
  21712. });
  21713. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21714. /**
  21715. * Gets the layer id use to find what meshes are not impacted by the light.
  21716. * Inactive if 0
  21717. */
  21718. get: function () {
  21719. return this._excludeWithLayerMask;
  21720. },
  21721. /**
  21722. * Sets the layer id use to find what meshes are not impacted by the light.
  21723. * Inactive if 0
  21724. */
  21725. set: function (value) {
  21726. this._excludeWithLayerMask = value;
  21727. this._resyncMeshes();
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21733. /**
  21734. * Gets the layer id use to find what meshes are impacted by the light.
  21735. * Inactive if 0
  21736. */
  21737. get: function () {
  21738. return this._includeOnlyWithLayerMask;
  21739. },
  21740. /**
  21741. * Sets the layer id use to find what meshes are impacted by the light.
  21742. * Inactive if 0
  21743. */
  21744. set: function (value) {
  21745. this._includeOnlyWithLayerMask = value;
  21746. this._resyncMeshes();
  21747. },
  21748. enumerable: true,
  21749. configurable: true
  21750. });
  21751. Object.defineProperty(Light.prototype, "lightmapMode", {
  21752. /**
  21753. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21754. */
  21755. get: function () {
  21756. return this._lightmapMode;
  21757. },
  21758. /**
  21759. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21760. */
  21761. set: function (value) {
  21762. if (this._lightmapMode === value) {
  21763. return;
  21764. }
  21765. this._lightmapMode = value;
  21766. this._markMeshesAsLightDirty();
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. /**
  21772. * Returns the string "Light".
  21773. * @returns the class name
  21774. */
  21775. Light.prototype.getClassName = function () {
  21776. return "Light";
  21777. };
  21778. /**
  21779. * Converts the light information to a readable string for debug purpose.
  21780. * @param fullDetails Supports for multiple levels of logging within scene loading
  21781. * @returns the human readable light info
  21782. */
  21783. Light.prototype.toString = function (fullDetails) {
  21784. var ret = "Name: " + this.name;
  21785. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21786. if (this.animations) {
  21787. for (var i = 0; i < this.animations.length; i++) {
  21788. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21789. }
  21790. }
  21791. if (fullDetails) {
  21792. }
  21793. return ret;
  21794. };
  21795. /**
  21796. * Set the enabled state of this node.
  21797. * @param value - the new enabled state
  21798. */
  21799. Light.prototype.setEnabled = function (value) {
  21800. _super.prototype.setEnabled.call(this, value);
  21801. this._resyncMeshes();
  21802. };
  21803. /**
  21804. * Returns the Light associated shadow generator if any.
  21805. * @return the associated shadow generator.
  21806. */
  21807. Light.prototype.getShadowGenerator = function () {
  21808. return this._shadowGenerator;
  21809. };
  21810. /**
  21811. * Returns a Vector3, the absolute light position in the World.
  21812. * @returns the world space position of the light
  21813. */
  21814. Light.prototype.getAbsolutePosition = function () {
  21815. return BABYLON.Vector3.Zero();
  21816. };
  21817. /**
  21818. * Specifies if the light will affect the passed mesh.
  21819. * @param mesh The mesh to test against the light
  21820. * @return true the mesh is affected otherwise, false.
  21821. */
  21822. Light.prototype.canAffectMesh = function (mesh) {
  21823. if (!mesh) {
  21824. return true;
  21825. }
  21826. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21827. return false;
  21828. }
  21829. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21830. return false;
  21831. }
  21832. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21833. return false;
  21834. }
  21835. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21836. return false;
  21837. }
  21838. return true;
  21839. };
  21840. /**
  21841. * Computes and Returns the light World matrix.
  21842. * @returns the world matrix
  21843. */
  21844. Light.prototype.getWorldMatrix = function () {
  21845. this._currentRenderId = this.getScene().getRenderId();
  21846. this._childRenderId = this._currentRenderId;
  21847. var worldMatrix = this._getWorldMatrix();
  21848. if (this.parent && this.parent.getWorldMatrix) {
  21849. if (!this._parentedWorldMatrix) {
  21850. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21851. }
  21852. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21853. this._markSyncedWithParent();
  21854. return this._parentedWorldMatrix;
  21855. }
  21856. return worldMatrix;
  21857. };
  21858. /**
  21859. * Sort function to order lights for rendering.
  21860. * @param a First Light object to compare to second.
  21861. * @param b Second Light object to compare first.
  21862. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21863. */
  21864. Light.CompareLightsPriority = function (a, b) {
  21865. //shadow-casting lights have priority over non-shadow-casting lights
  21866. //the renderPrioirty is a secondary sort criterion
  21867. if (a.shadowEnabled !== b.shadowEnabled) {
  21868. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21869. }
  21870. return b.renderPriority - a.renderPriority;
  21871. };
  21872. /**
  21873. * Releases resources associated with this node.
  21874. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21875. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21876. */
  21877. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21878. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21879. if (this._shadowGenerator) {
  21880. this._shadowGenerator.dispose();
  21881. this._shadowGenerator = null;
  21882. }
  21883. // Animations
  21884. this.getScene().stopAnimation(this);
  21885. // Remove from meshes
  21886. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21887. var mesh = _a[_i];
  21888. mesh._removeLightSource(this);
  21889. }
  21890. this._uniformBuffer.dispose();
  21891. // Remove from scene
  21892. this.getScene().removeLight(this);
  21893. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21894. };
  21895. /**
  21896. * Returns the light type ID (integer).
  21897. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21898. */
  21899. Light.prototype.getTypeID = function () {
  21900. return 0;
  21901. };
  21902. /**
  21903. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21904. * @returns the scaled intensity in intensity mode unit
  21905. */
  21906. Light.prototype.getScaledIntensity = function () {
  21907. return this._photometricScale * this.intensity;
  21908. };
  21909. /**
  21910. * Returns a new Light object, named "name", from the current one.
  21911. * @param name The name of the cloned light
  21912. * @returns the new created light
  21913. */
  21914. Light.prototype.clone = function (name) {
  21915. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21916. if (!constructor) {
  21917. return null;
  21918. }
  21919. return BABYLON.SerializationHelper.Clone(constructor, this);
  21920. };
  21921. /**
  21922. * Serializes the current light into a Serialization object.
  21923. * @returns the serialized object.
  21924. */
  21925. Light.prototype.serialize = function () {
  21926. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21927. // Type
  21928. serializationObject.type = this.getTypeID();
  21929. // Parent
  21930. if (this.parent) {
  21931. serializationObject.parentId = this.parent.id;
  21932. }
  21933. // Inclusion / exclusions
  21934. if (this.excludedMeshes.length > 0) {
  21935. serializationObject.excludedMeshesIds = [];
  21936. this.excludedMeshes.forEach(function (mesh) {
  21937. serializationObject.excludedMeshesIds.push(mesh.id);
  21938. });
  21939. }
  21940. if (this.includedOnlyMeshes.length > 0) {
  21941. serializationObject.includedOnlyMeshesIds = [];
  21942. this.includedOnlyMeshes.forEach(function (mesh) {
  21943. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21944. });
  21945. }
  21946. // Animations
  21947. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21948. serializationObject.ranges = this.serializeAnimationRanges();
  21949. return serializationObject;
  21950. };
  21951. /**
  21952. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21953. * This new light is named "name" and added to the passed scene.
  21954. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21955. * @param name The friendly name of the light
  21956. * @param scene The scene the new light will belong to
  21957. * @returns the constructor function
  21958. */
  21959. Light.GetConstructorFromName = function (type, name, scene) {
  21960. switch (type) {
  21961. case 0:
  21962. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21963. case 1:
  21964. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21965. case 2:
  21966. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21967. case 3:
  21968. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21969. }
  21970. return null;
  21971. };
  21972. /**
  21973. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21974. * @param parsedLight The JSON representation of the light
  21975. * @param scene The scene to create the parsed light in
  21976. * @returns the created light after parsing
  21977. */
  21978. Light.Parse = function (parsedLight, scene) {
  21979. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21980. if (!constructor) {
  21981. return null;
  21982. }
  21983. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21984. // Inclusion / exclusions
  21985. if (parsedLight.excludedMeshesIds) {
  21986. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21987. }
  21988. if (parsedLight.includedOnlyMeshesIds) {
  21989. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21990. }
  21991. // Parent
  21992. if (parsedLight.parentId) {
  21993. light._waitingParentId = parsedLight.parentId;
  21994. }
  21995. // Animations
  21996. if (parsedLight.animations) {
  21997. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21998. var parsedAnimation = parsedLight.animations[animationIndex];
  21999. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22000. }
  22001. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22002. }
  22003. if (parsedLight.autoAnimate) {
  22004. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22005. }
  22006. return light;
  22007. };
  22008. Light.prototype._hookArrayForExcluded = function (array) {
  22009. var _this = this;
  22010. var oldPush = array.push;
  22011. array.push = function () {
  22012. var items = [];
  22013. for (var _i = 0; _i < arguments.length; _i++) {
  22014. items[_i] = arguments[_i];
  22015. }
  22016. var result = oldPush.apply(array, items);
  22017. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22018. var item = items_1[_a];
  22019. item._resyncLighSource(_this);
  22020. }
  22021. return result;
  22022. };
  22023. var oldSplice = array.splice;
  22024. array.splice = function (index, deleteCount) {
  22025. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22026. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22027. var item = deleted_1[_i];
  22028. item._resyncLighSource(_this);
  22029. }
  22030. return deleted;
  22031. };
  22032. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22033. var item = array_1[_i];
  22034. item._resyncLighSource(this);
  22035. }
  22036. };
  22037. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22038. var _this = this;
  22039. var oldPush = array.push;
  22040. array.push = function () {
  22041. var items = [];
  22042. for (var _i = 0; _i < arguments.length; _i++) {
  22043. items[_i] = arguments[_i];
  22044. }
  22045. var result = oldPush.apply(array, items);
  22046. _this._resyncMeshes();
  22047. return result;
  22048. };
  22049. var oldSplice = array.splice;
  22050. array.splice = function (index, deleteCount) {
  22051. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22052. _this._resyncMeshes();
  22053. return deleted;
  22054. };
  22055. this._resyncMeshes();
  22056. };
  22057. Light.prototype._resyncMeshes = function () {
  22058. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22059. var mesh = _a[_i];
  22060. mesh._resyncLighSource(this);
  22061. }
  22062. };
  22063. /**
  22064. * Forces the meshes to update their light related information in their rendering used effects
  22065. * @hidden Internal Use Only
  22066. */
  22067. Light.prototype._markMeshesAsLightDirty = function () {
  22068. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22069. var mesh = _a[_i];
  22070. if (mesh._lightSources.indexOf(this) !== -1) {
  22071. mesh._markSubMeshesAsLightDirty();
  22072. }
  22073. }
  22074. };
  22075. /**
  22076. * Recomputes the cached photometric scale if needed.
  22077. */
  22078. Light.prototype._computePhotometricScale = function () {
  22079. this._photometricScale = this._getPhotometricScale();
  22080. this.getScene().resetCachedMaterial();
  22081. };
  22082. /**
  22083. * Returns the Photometric Scale according to the light type and intensity mode.
  22084. */
  22085. Light.prototype._getPhotometricScale = function () {
  22086. var photometricScale = 0.0;
  22087. var lightTypeID = this.getTypeID();
  22088. //get photometric mode
  22089. var photometricMode = this.intensityMode;
  22090. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22091. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22092. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22093. }
  22094. else {
  22095. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22096. }
  22097. }
  22098. //compute photometric scale
  22099. switch (lightTypeID) {
  22100. case Light.LIGHTTYPEID_POINTLIGHT:
  22101. case Light.LIGHTTYPEID_SPOTLIGHT:
  22102. switch (photometricMode) {
  22103. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22104. photometricScale = 1.0 / (4.0 * Math.PI);
  22105. break;
  22106. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22107. photometricScale = 1.0;
  22108. break;
  22109. case Light.INTENSITYMODE_LUMINANCE:
  22110. photometricScale = this.radius * this.radius;
  22111. break;
  22112. }
  22113. break;
  22114. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22115. switch (photometricMode) {
  22116. case Light.INTENSITYMODE_ILLUMINANCE:
  22117. photometricScale = 1.0;
  22118. break;
  22119. case Light.INTENSITYMODE_LUMINANCE:
  22120. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22121. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22122. var apexAngleRadians = this.radius;
  22123. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22124. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22125. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22126. photometricScale = solidAngle;
  22127. break;
  22128. }
  22129. break;
  22130. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22131. // No fall off in hemisperic light.
  22132. photometricScale = 1.0;
  22133. break;
  22134. }
  22135. return photometricScale;
  22136. };
  22137. /**
  22138. * Reorder the light in the scene according to their defined priority.
  22139. * @hidden Internal Use Only
  22140. */
  22141. Light.prototype._reorderLightsInScene = function () {
  22142. var scene = this.getScene();
  22143. if (this._renderPriority != 0) {
  22144. scene.requireLightSorting = true;
  22145. }
  22146. this.getScene().sortLightsByPriority();
  22147. };
  22148. //lightmapMode Consts
  22149. Light._LIGHTMAP_DEFAULT = 0;
  22150. Light._LIGHTMAP_SPECULAR = 1;
  22151. Light._LIGHTMAP_SHADOWSONLY = 2;
  22152. // Intensity Mode Consts
  22153. Light._INTENSITYMODE_AUTOMATIC = 0;
  22154. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22155. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22156. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22157. Light._INTENSITYMODE_LUMINANCE = 4;
  22158. // Light types ids const.
  22159. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22160. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22161. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22162. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22163. __decorate([
  22164. BABYLON.serializeAsColor3()
  22165. ], Light.prototype, "diffuse", void 0);
  22166. __decorate([
  22167. BABYLON.serializeAsColor3()
  22168. ], Light.prototype, "specular", void 0);
  22169. __decorate([
  22170. BABYLON.serialize()
  22171. ], Light.prototype, "intensity", void 0);
  22172. __decorate([
  22173. BABYLON.serialize()
  22174. ], Light.prototype, "range", void 0);
  22175. __decorate([
  22176. BABYLON.serialize()
  22177. ], Light.prototype, "intensityMode", null);
  22178. __decorate([
  22179. BABYLON.serialize()
  22180. ], Light.prototype, "radius", null);
  22181. __decorate([
  22182. BABYLON.serialize()
  22183. ], Light.prototype, "_renderPriority", void 0);
  22184. __decorate([
  22185. BABYLON.expandToProperty("_reorderLightsInScene")
  22186. ], Light.prototype, "renderPriority", void 0);
  22187. __decorate([
  22188. BABYLON.serialize("shadowEnabled")
  22189. ], Light.prototype, "_shadowEnabled", void 0);
  22190. __decorate([
  22191. BABYLON.serialize("excludeWithLayerMask")
  22192. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22193. __decorate([
  22194. BABYLON.serialize("includeOnlyWithLayerMask")
  22195. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22196. __decorate([
  22197. BABYLON.serialize("lightmapMode")
  22198. ], Light.prototype, "_lightmapMode", void 0);
  22199. return Light;
  22200. }(BABYLON.Node));
  22201. BABYLON.Light = Light;
  22202. })(BABYLON || (BABYLON = {}));
  22203. //# sourceMappingURL=babylon.light.js.map
  22204. var BABYLON;
  22205. (function (BABYLON) {
  22206. var Camera = /** @class */ (function (_super) {
  22207. __extends(Camera, _super);
  22208. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22209. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22210. var _this = _super.call(this, name, scene) || this;
  22211. /**
  22212. * The vector the camera should consider as up.
  22213. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22214. */
  22215. _this.upVector = BABYLON.Vector3.Up();
  22216. _this.orthoLeft = null;
  22217. _this.orthoRight = null;
  22218. _this.orthoBottom = null;
  22219. _this.orthoTop = null;
  22220. /**
  22221. * FOV is set in Radians. (default is 0.8)
  22222. */
  22223. _this.fov = 0.8;
  22224. _this.minZ = 1;
  22225. _this.maxZ = 10000.0;
  22226. _this.inertia = 0.9;
  22227. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22228. _this.isIntermediate = false;
  22229. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22230. /**
  22231. * Restricts the camera to viewing objects with the same layerMask.
  22232. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22233. */
  22234. _this.layerMask = 0x0FFFFFFF;
  22235. /**
  22236. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22237. */
  22238. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22239. // Camera rig members
  22240. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22241. _this._rigCameras = new Array();
  22242. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22243. _this._skipRendering = false;
  22244. _this.customRenderTargets = new Array();
  22245. // Observables
  22246. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22247. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22248. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22249. _this.onRestoreStateObservable = new BABYLON.Observable();
  22250. // Cache
  22251. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22252. _this._projectionMatrix = new BABYLON.Matrix();
  22253. _this._doNotComputeProjectionMatrix = false;
  22254. _this._worldMatrix = BABYLON.Matrix.Identity();
  22255. _this._postProcesses = new Array();
  22256. _this._transformMatrix = BABYLON.Matrix.Zero();
  22257. _this._activeMeshes = new BABYLON.SmartArray(256);
  22258. _this._globalPosition = BABYLON.Vector3.Zero();
  22259. _this._refreshFrustumPlanes = true;
  22260. _this.getScene().addCamera(_this);
  22261. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22262. _this.getScene().activeCamera = _this;
  22263. }
  22264. _this.position = position;
  22265. return _this;
  22266. }
  22267. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22268. get: function () {
  22269. return Camera._PERSPECTIVE_CAMERA;
  22270. },
  22271. enumerable: true,
  22272. configurable: true
  22273. });
  22274. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22275. get: function () {
  22276. return Camera._ORTHOGRAPHIC_CAMERA;
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22282. /**
  22283. * This is the default FOV mode for perspective cameras.
  22284. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22285. *
  22286. */
  22287. get: function () {
  22288. return Camera._FOVMODE_VERTICAL_FIXED;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22294. /**
  22295. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22296. *
  22297. */
  22298. get: function () {
  22299. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22305. get: function () {
  22306. return Camera._RIG_MODE_NONE;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22312. get: function () {
  22313. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22319. get: function () {
  22320. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22326. get: function () {
  22327. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22328. },
  22329. enumerable: true,
  22330. configurable: true
  22331. });
  22332. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22333. get: function () {
  22334. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22340. get: function () {
  22341. return Camera._RIG_MODE_VR;
  22342. },
  22343. enumerable: true,
  22344. configurable: true
  22345. });
  22346. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22347. get: function () {
  22348. return Camera._RIG_MODE_WEBVR;
  22349. },
  22350. enumerable: true,
  22351. configurable: true
  22352. });
  22353. /**
  22354. * Store current camera state (fov, position, etc..)
  22355. */
  22356. Camera.prototype.storeState = function () {
  22357. this._stateStored = true;
  22358. this._storedFov = this.fov;
  22359. return this;
  22360. };
  22361. /**
  22362. * Restores the camera state values if it has been stored. You must call storeState() first
  22363. */
  22364. Camera.prototype._restoreStateValues = function () {
  22365. if (!this._stateStored) {
  22366. return false;
  22367. }
  22368. this.fov = this._storedFov;
  22369. return true;
  22370. };
  22371. /**
  22372. * Restored camera state. You must call storeState() first
  22373. */
  22374. Camera.prototype.restoreState = function () {
  22375. if (this._restoreStateValues()) {
  22376. this.onRestoreStateObservable.notifyObservers(this);
  22377. return true;
  22378. }
  22379. return false;
  22380. };
  22381. Camera.prototype.getClassName = function () {
  22382. return "Camera";
  22383. };
  22384. /**
  22385. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22386. */
  22387. Camera.prototype.toString = function (fullDetails) {
  22388. var ret = "Name: " + this.name;
  22389. ret += ", type: " + this.getClassName();
  22390. if (this.animations) {
  22391. for (var i = 0; i < this.animations.length; i++) {
  22392. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22393. }
  22394. }
  22395. if (fullDetails) {
  22396. }
  22397. return ret;
  22398. };
  22399. Object.defineProperty(Camera.prototype, "globalPosition", {
  22400. get: function () {
  22401. return this._globalPosition;
  22402. },
  22403. enumerable: true,
  22404. configurable: true
  22405. });
  22406. Camera.prototype.getActiveMeshes = function () {
  22407. return this._activeMeshes;
  22408. };
  22409. Camera.prototype.isActiveMesh = function (mesh) {
  22410. return (this._activeMeshes.indexOf(mesh) !== -1);
  22411. };
  22412. /**
  22413. * Is this camera ready to be used/rendered
  22414. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22415. * @return true if the camera is ready
  22416. */
  22417. Camera.prototype.isReady = function (completeCheck) {
  22418. if (completeCheck === void 0) { completeCheck = false; }
  22419. if (completeCheck) {
  22420. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22421. var pp = _a[_i];
  22422. if (pp && !pp.isReady()) {
  22423. return false;
  22424. }
  22425. }
  22426. }
  22427. return _super.prototype.isReady.call(this, completeCheck);
  22428. };
  22429. //Cache
  22430. Camera.prototype._initCache = function () {
  22431. _super.prototype._initCache.call(this);
  22432. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22433. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22434. this._cache.mode = undefined;
  22435. this._cache.minZ = undefined;
  22436. this._cache.maxZ = undefined;
  22437. this._cache.fov = undefined;
  22438. this._cache.fovMode = undefined;
  22439. this._cache.aspectRatio = undefined;
  22440. this._cache.orthoLeft = undefined;
  22441. this._cache.orthoRight = undefined;
  22442. this._cache.orthoBottom = undefined;
  22443. this._cache.orthoTop = undefined;
  22444. this._cache.renderWidth = undefined;
  22445. this._cache.renderHeight = undefined;
  22446. };
  22447. Camera.prototype._updateCache = function (ignoreParentClass) {
  22448. if (!ignoreParentClass) {
  22449. _super.prototype._updateCache.call(this);
  22450. }
  22451. this._cache.position.copyFrom(this.position);
  22452. this._cache.upVector.copyFrom(this.upVector);
  22453. };
  22454. // Synchronized
  22455. Camera.prototype._isSynchronized = function () {
  22456. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22457. };
  22458. Camera.prototype._isSynchronizedViewMatrix = function () {
  22459. if (!_super.prototype._isSynchronized.call(this))
  22460. return false;
  22461. return this._cache.position.equals(this.position)
  22462. && this._cache.upVector.equals(this.upVector)
  22463. && this.isSynchronizedWithParent();
  22464. };
  22465. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22466. var check = this._cache.mode === this.mode
  22467. && this._cache.minZ === this.minZ
  22468. && this._cache.maxZ === this.maxZ;
  22469. if (!check) {
  22470. return false;
  22471. }
  22472. var engine = this.getEngine();
  22473. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22474. check = this._cache.fov === this.fov
  22475. && this._cache.fovMode === this.fovMode
  22476. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22477. }
  22478. else {
  22479. check = this._cache.orthoLeft === this.orthoLeft
  22480. && this._cache.orthoRight === this.orthoRight
  22481. && this._cache.orthoBottom === this.orthoBottom
  22482. && this._cache.orthoTop === this.orthoTop
  22483. && this._cache.renderWidth === engine.getRenderWidth()
  22484. && this._cache.renderHeight === engine.getRenderHeight();
  22485. }
  22486. return check;
  22487. };
  22488. // Controls
  22489. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22490. };
  22491. Camera.prototype.detachControl = function (element) {
  22492. };
  22493. Camera.prototype.update = function () {
  22494. this._checkInputs();
  22495. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22496. this._updateRigCameras();
  22497. }
  22498. };
  22499. Camera.prototype._checkInputs = function () {
  22500. this.onAfterCheckInputsObservable.notifyObservers(this);
  22501. };
  22502. Object.defineProperty(Camera.prototype, "rigCameras", {
  22503. get: function () {
  22504. return this._rigCameras;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22510. get: function () {
  22511. return this._rigPostProcess;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. /**
  22517. * Internal, gets the first post proces.
  22518. * @returns the first post process to be run on this camera.
  22519. */
  22520. Camera.prototype._getFirstPostProcess = function () {
  22521. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22522. if (this._postProcesses[ppIndex] !== null) {
  22523. return this._postProcesses[ppIndex];
  22524. }
  22525. }
  22526. return null;
  22527. };
  22528. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22529. // invalidate framebuffer
  22530. var firstPostProcess = this._getFirstPostProcess();
  22531. if (firstPostProcess) {
  22532. firstPostProcess.markTextureDirty();
  22533. }
  22534. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22535. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22536. var cam = this._rigCameras[i];
  22537. var rigPostProcess = cam._rigPostProcess;
  22538. // for VR rig, there does not have to be a post process
  22539. if (rigPostProcess) {
  22540. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22541. if (isPass) {
  22542. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22543. cam.isIntermediate = this._postProcesses.length === 0;
  22544. }
  22545. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22546. rigPostProcess.markTextureDirty();
  22547. }
  22548. else {
  22549. cam._postProcesses = this._postProcesses.slice(0);
  22550. }
  22551. }
  22552. };
  22553. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22554. if (insertAt === void 0) { insertAt = null; }
  22555. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22556. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22557. return 0;
  22558. }
  22559. if (insertAt == null || insertAt < 0) {
  22560. this._postProcesses.push(postProcess);
  22561. }
  22562. else if (this._postProcesses[insertAt] === null) {
  22563. this._postProcesses[insertAt] = postProcess;
  22564. }
  22565. else {
  22566. this._postProcesses.splice(insertAt, 0, postProcess);
  22567. }
  22568. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22569. return this._postProcesses.indexOf(postProcess);
  22570. };
  22571. Camera.prototype.detachPostProcess = function (postProcess) {
  22572. var idx = this._postProcesses.indexOf(postProcess);
  22573. if (idx !== -1) {
  22574. this._postProcesses[idx] = null;
  22575. }
  22576. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22577. };
  22578. Camera.prototype.getWorldMatrix = function () {
  22579. if (this._isSynchronizedViewMatrix()) {
  22580. return this._worldMatrix;
  22581. }
  22582. // Getting the the view matrix will also compute the world matrix.
  22583. this.getViewMatrix();
  22584. return this._worldMatrix;
  22585. };
  22586. Camera.prototype._getViewMatrix = function () {
  22587. return BABYLON.Matrix.Identity();
  22588. };
  22589. Camera.prototype.getViewMatrix = function (force) {
  22590. if (!force && this._isSynchronizedViewMatrix()) {
  22591. return this._computedViewMatrix;
  22592. }
  22593. this.updateCache();
  22594. this._computedViewMatrix = this._getViewMatrix();
  22595. this._currentRenderId = this.getScene().getRenderId();
  22596. this._childRenderId = this._currentRenderId;
  22597. this._refreshFrustumPlanes = true;
  22598. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22599. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22600. }
  22601. this.onViewMatrixChangedObservable.notifyObservers(this);
  22602. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22603. return this._computedViewMatrix;
  22604. };
  22605. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22606. this._doNotComputeProjectionMatrix = true;
  22607. if (projection !== undefined) {
  22608. this._projectionMatrix = projection;
  22609. }
  22610. };
  22611. ;
  22612. Camera.prototype.unfreezeProjectionMatrix = function () {
  22613. this._doNotComputeProjectionMatrix = false;
  22614. };
  22615. ;
  22616. Camera.prototype.getProjectionMatrix = function (force) {
  22617. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22618. return this._projectionMatrix;
  22619. }
  22620. // Cache
  22621. this._cache.mode = this.mode;
  22622. this._cache.minZ = this.minZ;
  22623. this._cache.maxZ = this.maxZ;
  22624. // Matrix
  22625. this._refreshFrustumPlanes = true;
  22626. var engine = this.getEngine();
  22627. var scene = this.getScene();
  22628. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22629. this._cache.fov = this.fov;
  22630. this._cache.fovMode = this.fovMode;
  22631. this._cache.aspectRatio = engine.getAspectRatio(this);
  22632. if (this.minZ <= 0) {
  22633. this.minZ = 0.1;
  22634. }
  22635. if (scene.useRightHandedSystem) {
  22636. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22637. }
  22638. else {
  22639. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22640. }
  22641. }
  22642. else {
  22643. var halfWidth = engine.getRenderWidth() / 2.0;
  22644. var halfHeight = engine.getRenderHeight() / 2.0;
  22645. if (scene.useRightHandedSystem) {
  22646. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22647. }
  22648. else {
  22649. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22650. }
  22651. this._cache.orthoLeft = this.orthoLeft;
  22652. this._cache.orthoRight = this.orthoRight;
  22653. this._cache.orthoBottom = this.orthoBottom;
  22654. this._cache.orthoTop = this.orthoTop;
  22655. this._cache.renderWidth = engine.getRenderWidth();
  22656. this._cache.renderHeight = engine.getRenderHeight();
  22657. }
  22658. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22659. return this._projectionMatrix;
  22660. };
  22661. Camera.prototype.getTranformationMatrix = function () {
  22662. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22663. return this._transformMatrix;
  22664. };
  22665. Camera.prototype.updateFrustumPlanes = function () {
  22666. if (!this._refreshFrustumPlanes) {
  22667. return;
  22668. }
  22669. this.getTranformationMatrix();
  22670. if (!this._frustumPlanes) {
  22671. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22672. }
  22673. else {
  22674. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22675. }
  22676. this._refreshFrustumPlanes = false;
  22677. };
  22678. Camera.prototype.isInFrustum = function (target) {
  22679. this.updateFrustumPlanes();
  22680. return target.isInFrustum(this._frustumPlanes);
  22681. };
  22682. Camera.prototype.isCompletelyInFrustum = function (target) {
  22683. this.updateFrustumPlanes();
  22684. return target.isCompletelyInFrustum(this._frustumPlanes);
  22685. };
  22686. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22687. if (length === void 0) { length = 100; }
  22688. if (!transform) {
  22689. transform = this.getWorldMatrix();
  22690. }
  22691. if (!origin) {
  22692. origin = this.position;
  22693. }
  22694. var forward = new BABYLON.Vector3(0, 0, 1);
  22695. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22696. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22697. return new BABYLON.Ray(origin, direction, length);
  22698. };
  22699. /**
  22700. * Releases resources associated with this node.
  22701. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22702. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22703. */
  22704. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22705. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22706. // Observables
  22707. this.onViewMatrixChangedObservable.clear();
  22708. this.onProjectionMatrixChangedObservable.clear();
  22709. this.onAfterCheckInputsObservable.clear();
  22710. this.onRestoreStateObservable.clear();
  22711. // Inputs
  22712. if (this.inputs) {
  22713. this.inputs.clear();
  22714. }
  22715. // Animations
  22716. this.getScene().stopAnimation(this);
  22717. // Remove from scene
  22718. this.getScene().removeCamera(this);
  22719. while (this._rigCameras.length > 0) {
  22720. var camera = this._rigCameras.pop();
  22721. if (camera) {
  22722. camera.dispose();
  22723. }
  22724. }
  22725. // Postprocesses
  22726. if (this._rigPostProcess) {
  22727. this._rigPostProcess.dispose(this);
  22728. this._rigPostProcess = null;
  22729. this._postProcesses = [];
  22730. }
  22731. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22732. this._rigPostProcess = null;
  22733. this._postProcesses = [];
  22734. }
  22735. else {
  22736. var i = this._postProcesses.length;
  22737. while (--i >= 0) {
  22738. var postProcess = this._postProcesses[i];
  22739. if (postProcess) {
  22740. postProcess.dispose(this);
  22741. }
  22742. }
  22743. }
  22744. // Render targets
  22745. var i = this.customRenderTargets.length;
  22746. while (--i >= 0) {
  22747. this.customRenderTargets[i].dispose();
  22748. }
  22749. this.customRenderTargets = [];
  22750. // Active Meshes
  22751. this._activeMeshes.dispose();
  22752. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22753. };
  22754. Object.defineProperty(Camera.prototype, "leftCamera", {
  22755. // ---- Camera rigs section ----
  22756. get: function () {
  22757. if (this._rigCameras.length < 1) {
  22758. return null;
  22759. }
  22760. return this._rigCameras[0];
  22761. },
  22762. enumerable: true,
  22763. configurable: true
  22764. });
  22765. Object.defineProperty(Camera.prototype, "rightCamera", {
  22766. get: function () {
  22767. if (this._rigCameras.length < 2) {
  22768. return null;
  22769. }
  22770. return this._rigCameras[1];
  22771. },
  22772. enumerable: true,
  22773. configurable: true
  22774. });
  22775. Camera.prototype.getLeftTarget = function () {
  22776. if (this._rigCameras.length < 1) {
  22777. return null;
  22778. }
  22779. return this._rigCameras[0].getTarget();
  22780. };
  22781. Camera.prototype.getRightTarget = function () {
  22782. if (this._rigCameras.length < 2) {
  22783. return null;
  22784. }
  22785. return this._rigCameras[1].getTarget();
  22786. };
  22787. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22788. if (this.cameraRigMode === mode) {
  22789. return;
  22790. }
  22791. while (this._rigCameras.length > 0) {
  22792. var camera = this._rigCameras.pop();
  22793. if (camera) {
  22794. camera.dispose();
  22795. }
  22796. }
  22797. this.cameraRigMode = mode;
  22798. this._cameraRigParams = {};
  22799. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22800. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22801. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22802. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22803. // create the rig cameras, unless none
  22804. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22805. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22806. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22807. if (leftCamera && rightCamera) {
  22808. this._rigCameras.push(leftCamera);
  22809. this._rigCameras.push(rightCamera);
  22810. }
  22811. }
  22812. switch (this.cameraRigMode) {
  22813. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22814. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22815. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22816. break;
  22817. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22818. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22819. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22820. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22821. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22822. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22823. break;
  22824. case Camera.RIG_MODE_VR:
  22825. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22826. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22827. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22828. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22829. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22830. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22831. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22832. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22833. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22834. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22835. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22836. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22837. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22838. if (metrics.compensateDistortion) {
  22839. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22840. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22841. }
  22842. break;
  22843. case Camera.RIG_MODE_WEBVR:
  22844. if (rigParams.vrDisplay) {
  22845. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22846. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22847. //Left eye
  22848. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22849. this._rigCameras[0].setCameraRigParameter("left", true);
  22850. //leaving this for future reference
  22851. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22852. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22853. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22854. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22855. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22856. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22857. this._rigCameras[0].parent = this;
  22858. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22859. //Right eye
  22860. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22861. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22862. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22863. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22864. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22865. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22866. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22867. this._rigCameras[1].parent = this;
  22868. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22869. if (Camera.UseAlternateWebVRRendering) {
  22870. this._rigCameras[1]._skipRendering = true;
  22871. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22872. }
  22873. }
  22874. break;
  22875. }
  22876. this._cascadePostProcessesToRigCams();
  22877. this.update();
  22878. };
  22879. Camera.prototype._getVRProjectionMatrix = function () {
  22880. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22881. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22882. return this._projectionMatrix;
  22883. };
  22884. Camera.prototype._updateCameraRotationMatrix = function () {
  22885. //Here for WebVR
  22886. };
  22887. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22888. //Here for WebVR
  22889. };
  22890. /**
  22891. * This function MUST be overwritten by the different WebVR cameras available.
  22892. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22893. */
  22894. Camera.prototype._getWebVRProjectionMatrix = function () {
  22895. return BABYLON.Matrix.Identity();
  22896. };
  22897. /**
  22898. * This function MUST be overwritten by the different WebVR cameras available.
  22899. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22900. */
  22901. Camera.prototype._getWebVRViewMatrix = function () {
  22902. return BABYLON.Matrix.Identity();
  22903. };
  22904. Camera.prototype.setCameraRigParameter = function (name, value) {
  22905. if (!this._cameraRigParams) {
  22906. this._cameraRigParams = {};
  22907. }
  22908. this._cameraRigParams[name] = value;
  22909. //provisionnally:
  22910. if (name === "interaxialDistance") {
  22911. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22912. }
  22913. };
  22914. /**
  22915. * needs to be overridden by children so sub has required properties to be copied
  22916. */
  22917. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22918. return null;
  22919. };
  22920. /**
  22921. * May need to be overridden by children
  22922. */
  22923. Camera.prototype._updateRigCameras = function () {
  22924. for (var i = 0; i < this._rigCameras.length; i++) {
  22925. this._rigCameras[i].minZ = this.minZ;
  22926. this._rigCameras[i].maxZ = this.maxZ;
  22927. this._rigCameras[i].fov = this.fov;
  22928. }
  22929. // only update viewport when ANAGLYPH
  22930. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22931. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22932. }
  22933. };
  22934. Camera.prototype._setupInputs = function () {
  22935. };
  22936. Camera.prototype.serialize = function () {
  22937. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22938. // Type
  22939. serializationObject.type = this.getClassName();
  22940. // Parent
  22941. if (this.parent) {
  22942. serializationObject.parentId = this.parent.id;
  22943. }
  22944. if (this.inputs) {
  22945. this.inputs.serialize(serializationObject);
  22946. }
  22947. // Animations
  22948. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22949. serializationObject.ranges = this.serializeAnimationRanges();
  22950. return serializationObject;
  22951. };
  22952. Camera.prototype.clone = function (name) {
  22953. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22954. };
  22955. Camera.prototype.getDirection = function (localAxis) {
  22956. var result = BABYLON.Vector3.Zero();
  22957. this.getDirectionToRef(localAxis, result);
  22958. return result;
  22959. };
  22960. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22961. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22962. };
  22963. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22964. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22965. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22966. switch (type) {
  22967. case "ArcRotateCamera":
  22968. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22969. case "DeviceOrientationCamera":
  22970. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22971. case "FollowCamera":
  22972. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22973. case "ArcFollowCamera":
  22974. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22975. case "GamepadCamera":
  22976. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22977. case "TouchCamera":
  22978. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22979. case "VirtualJoysticksCamera":
  22980. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22981. case "WebVRFreeCamera":
  22982. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22983. case "WebVRGamepadCamera":
  22984. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22985. case "VRDeviceOrientationFreeCamera":
  22986. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22987. case "VRDeviceOrientationGamepadCamera":
  22988. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22989. case "AnaglyphArcRotateCamera":
  22990. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22991. case "AnaglyphFreeCamera":
  22992. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22993. case "AnaglyphGamepadCamera":
  22994. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22995. case "AnaglyphUniversalCamera":
  22996. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22997. case "StereoscopicArcRotateCamera":
  22998. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22999. case "StereoscopicFreeCamera":
  23000. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23001. case "StereoscopicGamepadCamera":
  23002. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23003. case "StereoscopicUniversalCamera":
  23004. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23005. case "FreeCamera": // Forcing Universal here
  23006. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23007. default: // Universal Camera is the default value
  23008. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23009. }
  23010. };
  23011. Camera.prototype.computeWorldMatrix = function () {
  23012. return this.getWorldMatrix();
  23013. };
  23014. Camera.Parse = function (parsedCamera, scene) {
  23015. var type = parsedCamera.type;
  23016. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23017. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23018. // Parent
  23019. if (parsedCamera.parentId) {
  23020. camera._waitingParentId = parsedCamera.parentId;
  23021. }
  23022. //If camera has an input manager, let it parse inputs settings
  23023. if (camera.inputs) {
  23024. camera.inputs.parse(parsedCamera);
  23025. camera._setupInputs();
  23026. }
  23027. if (camera.setPosition) { // need to force position
  23028. camera.position.copyFromFloats(0, 0, 0);
  23029. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23030. }
  23031. // Target
  23032. if (parsedCamera.target) {
  23033. if (camera.setTarget) {
  23034. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23035. }
  23036. }
  23037. // Apply 3d rig, when found
  23038. if (parsedCamera.cameraRigMode) {
  23039. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23040. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23041. }
  23042. // Animations
  23043. if (parsedCamera.animations) {
  23044. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23045. var parsedAnimation = parsedCamera.animations[animationIndex];
  23046. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23047. }
  23048. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23049. }
  23050. if (parsedCamera.autoAnimate) {
  23051. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23052. }
  23053. return camera;
  23054. };
  23055. // Statics
  23056. Camera._PERSPECTIVE_CAMERA = 0;
  23057. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23058. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23059. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23060. Camera._RIG_MODE_NONE = 0;
  23061. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23062. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23063. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23064. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23065. Camera._RIG_MODE_VR = 20;
  23066. Camera._RIG_MODE_WEBVR = 21;
  23067. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23068. Camera.UseAlternateWebVRRendering = false;
  23069. __decorate([
  23070. BABYLON.serializeAsVector3()
  23071. ], Camera.prototype, "position", void 0);
  23072. __decorate([
  23073. BABYLON.serializeAsVector3()
  23074. ], Camera.prototype, "upVector", void 0);
  23075. __decorate([
  23076. BABYLON.serialize()
  23077. ], Camera.prototype, "orthoLeft", void 0);
  23078. __decorate([
  23079. BABYLON.serialize()
  23080. ], Camera.prototype, "orthoRight", void 0);
  23081. __decorate([
  23082. BABYLON.serialize()
  23083. ], Camera.prototype, "orthoBottom", void 0);
  23084. __decorate([
  23085. BABYLON.serialize()
  23086. ], Camera.prototype, "orthoTop", void 0);
  23087. __decorate([
  23088. BABYLON.serialize()
  23089. ], Camera.prototype, "fov", void 0);
  23090. __decorate([
  23091. BABYLON.serialize()
  23092. ], Camera.prototype, "minZ", void 0);
  23093. __decorate([
  23094. BABYLON.serialize()
  23095. ], Camera.prototype, "maxZ", void 0);
  23096. __decorate([
  23097. BABYLON.serialize()
  23098. ], Camera.prototype, "inertia", void 0);
  23099. __decorate([
  23100. BABYLON.serialize()
  23101. ], Camera.prototype, "mode", void 0);
  23102. __decorate([
  23103. BABYLON.serialize()
  23104. ], Camera.prototype, "layerMask", void 0);
  23105. __decorate([
  23106. BABYLON.serialize()
  23107. ], Camera.prototype, "fovMode", void 0);
  23108. __decorate([
  23109. BABYLON.serialize()
  23110. ], Camera.prototype, "cameraRigMode", void 0);
  23111. __decorate([
  23112. BABYLON.serialize()
  23113. ], Camera.prototype, "interaxialDistance", void 0);
  23114. __decorate([
  23115. BABYLON.serialize()
  23116. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23117. return Camera;
  23118. }(BABYLON.Node));
  23119. BABYLON.Camera = Camera;
  23120. })(BABYLON || (BABYLON = {}));
  23121. //# sourceMappingURL=babylon.camera.js.map
  23122. var BABYLON;
  23123. (function (BABYLON) {
  23124. var RenderingManager = /** @class */ (function () {
  23125. function RenderingManager(scene) {
  23126. this._renderingGroups = new Array();
  23127. this._autoClearDepthStencil = {};
  23128. this._customOpaqueSortCompareFn = {};
  23129. this._customAlphaTestSortCompareFn = {};
  23130. this._customTransparentSortCompareFn = {};
  23131. this._renderinGroupInfo = null;
  23132. this._scene = scene;
  23133. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23134. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23135. }
  23136. }
  23137. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23138. if (depth === void 0) { depth = true; }
  23139. if (stencil === void 0) { stencil = true; }
  23140. if (this._depthStencilBufferAlreadyCleaned) {
  23141. return;
  23142. }
  23143. this._scene.getEngine().clear(null, false, depth, stencil);
  23144. this._depthStencilBufferAlreadyCleaned = true;
  23145. };
  23146. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23147. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23148. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23149. var info = null;
  23150. if (observable) {
  23151. if (!this._renderinGroupInfo) {
  23152. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23153. }
  23154. info = this._renderinGroupInfo;
  23155. info.scene = this._scene;
  23156. info.camera = this._scene.activeCamera;
  23157. }
  23158. // Dispatch sprites
  23159. if (renderSprites) {
  23160. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23161. var manager = this._scene.spriteManagers[index];
  23162. this.dispatchSprites(manager);
  23163. }
  23164. }
  23165. // Render
  23166. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23167. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23168. var renderingGroup = this._renderingGroups[index];
  23169. if (!renderingGroup && !observable)
  23170. continue;
  23171. var renderingGroupMask = 0;
  23172. // Fire PRECLEAR stage
  23173. if (observable && info) {
  23174. renderingGroupMask = Math.pow(2, index);
  23175. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23176. info.renderingGroupId = index;
  23177. observable.notifyObservers(info, renderingGroupMask);
  23178. }
  23179. // Clear depth/stencil if needed
  23180. if (RenderingManager.AUTOCLEAR) {
  23181. var autoClear = this._autoClearDepthStencil[index];
  23182. if (autoClear && autoClear.autoClear) {
  23183. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23184. }
  23185. }
  23186. if (observable && info) {
  23187. // Fire PREOPAQUE stage
  23188. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23189. observable.notifyObservers(info, renderingGroupMask);
  23190. // Fire PRETRANSPARENT stage
  23191. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23192. observable.notifyObservers(info, renderingGroupMask);
  23193. }
  23194. if (renderingGroup)
  23195. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23196. // Fire POSTTRANSPARENT stage
  23197. if (observable && info) {
  23198. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23199. observable.notifyObservers(info, renderingGroupMask);
  23200. }
  23201. }
  23202. };
  23203. RenderingManager.prototype.reset = function () {
  23204. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23205. var renderingGroup = this._renderingGroups[index];
  23206. if (renderingGroup) {
  23207. renderingGroup.prepare();
  23208. }
  23209. }
  23210. };
  23211. RenderingManager.prototype.dispose = function () {
  23212. this.freeRenderingGroups();
  23213. this._renderingGroups.length = 0;
  23214. };
  23215. /**
  23216. * Clear the info related to rendering groups preventing retention points during dispose.
  23217. */
  23218. RenderingManager.prototype.freeRenderingGroups = function () {
  23219. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23220. var renderingGroup = this._renderingGroups[index];
  23221. if (renderingGroup) {
  23222. renderingGroup.dispose();
  23223. }
  23224. }
  23225. };
  23226. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23227. if (this._renderingGroups[renderingGroupId] === undefined) {
  23228. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23229. }
  23230. };
  23231. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23232. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23233. this._prepareRenderingGroup(renderingGroupId);
  23234. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23235. };
  23236. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23237. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23238. this._prepareRenderingGroup(renderingGroupId);
  23239. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23240. };
  23241. /**
  23242. * @param subMesh The submesh to dispatch
  23243. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23244. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23245. */
  23246. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23247. if (mesh === undefined) {
  23248. mesh = subMesh.getMesh();
  23249. }
  23250. var renderingGroupId = mesh.renderingGroupId || 0;
  23251. this._prepareRenderingGroup(renderingGroupId);
  23252. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23253. };
  23254. /**
  23255. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23256. * This allowed control for front to back rendering or reversly depending of the special needs.
  23257. *
  23258. * @param renderingGroupId The rendering group id corresponding to its index
  23259. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23260. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23261. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23262. */
  23263. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23264. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23265. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23266. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23267. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23268. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23269. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23270. if (this._renderingGroups[renderingGroupId]) {
  23271. var group = this._renderingGroups[renderingGroupId];
  23272. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23273. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23274. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23275. }
  23276. };
  23277. /**
  23278. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23279. *
  23280. * @param renderingGroupId The rendering group id corresponding to its index
  23281. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23282. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23283. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23284. */
  23285. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23286. if (depth === void 0) { depth = true; }
  23287. if (stencil === void 0) { stencil = true; }
  23288. this._autoClearDepthStencil[renderingGroupId] = {
  23289. autoClear: autoClearDepthStencil,
  23290. depth: depth,
  23291. stencil: stencil
  23292. };
  23293. };
  23294. /**
  23295. * The max id used for rendering groups (not included)
  23296. */
  23297. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23298. /**
  23299. * The min id used for rendering groups (included)
  23300. */
  23301. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23302. /**
  23303. * Used to globally prevent autoclearing scenes.
  23304. */
  23305. RenderingManager.AUTOCLEAR = true;
  23306. return RenderingManager;
  23307. }());
  23308. BABYLON.RenderingManager = RenderingManager;
  23309. })(BABYLON || (BABYLON = {}));
  23310. //# sourceMappingURL=babylon.renderingManager.js.map
  23311. var BABYLON;
  23312. (function (BABYLON) {
  23313. var RenderingGroup = /** @class */ (function () {
  23314. /**
  23315. * Creates a new rendering group.
  23316. * @param index The rendering group index
  23317. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23318. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23319. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23320. */
  23321. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23322. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23323. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23324. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23325. this.index = index;
  23326. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23327. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23328. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23329. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23330. this._particleSystems = new BABYLON.SmartArray(256);
  23331. this._spriteManagers = new BABYLON.SmartArray(256);
  23332. this._edgesRenderers = new BABYLON.SmartArray(16);
  23333. this._scene = scene;
  23334. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23335. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23336. this.transparentSortCompareFn = transparentSortCompareFn;
  23337. }
  23338. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23339. /**
  23340. * Set the opaque sort comparison function.
  23341. * If null the sub meshes will be render in the order they were created
  23342. */
  23343. set: function (value) {
  23344. this._opaqueSortCompareFn = value;
  23345. if (value) {
  23346. this._renderOpaque = this.renderOpaqueSorted;
  23347. }
  23348. else {
  23349. this._renderOpaque = RenderingGroup.renderUnsorted;
  23350. }
  23351. },
  23352. enumerable: true,
  23353. configurable: true
  23354. });
  23355. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23356. /**
  23357. * Set the alpha test sort comparison function.
  23358. * If null the sub meshes will be render in the order they were created
  23359. */
  23360. set: function (value) {
  23361. this._alphaTestSortCompareFn = value;
  23362. if (value) {
  23363. this._renderAlphaTest = this.renderAlphaTestSorted;
  23364. }
  23365. else {
  23366. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23367. }
  23368. },
  23369. enumerable: true,
  23370. configurable: true
  23371. });
  23372. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23373. /**
  23374. * Set the transparent sort comparison function.
  23375. * If null the sub meshes will be render in the order they were created
  23376. */
  23377. set: function (value) {
  23378. if (value) {
  23379. this._transparentSortCompareFn = value;
  23380. }
  23381. else {
  23382. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23383. }
  23384. this._renderTransparent = this.renderTransparentSorted;
  23385. },
  23386. enumerable: true,
  23387. configurable: true
  23388. });
  23389. /**
  23390. * Render all the sub meshes contained in the group.
  23391. * @param customRenderFunction Used to override the default render behaviour of the group.
  23392. * @returns true if rendered some submeshes.
  23393. */
  23394. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23395. if (customRenderFunction) {
  23396. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23397. return;
  23398. }
  23399. var engine = this._scene.getEngine();
  23400. // Depth only
  23401. if (this._depthOnlySubMeshes.length !== 0) {
  23402. engine.setColorWrite(false);
  23403. this._renderAlphaTest(this._depthOnlySubMeshes);
  23404. engine.setColorWrite(true);
  23405. }
  23406. // Opaque
  23407. if (this._opaqueSubMeshes.length !== 0) {
  23408. this._renderOpaque(this._opaqueSubMeshes);
  23409. }
  23410. // Alpha test
  23411. if (this._alphaTestSubMeshes.length !== 0) {
  23412. this._renderAlphaTest(this._alphaTestSubMeshes);
  23413. }
  23414. var stencilState = engine.getStencilBuffer();
  23415. engine.setStencilBuffer(false);
  23416. // Sprites
  23417. if (renderSprites) {
  23418. this._renderSprites();
  23419. }
  23420. // Particles
  23421. if (renderParticles) {
  23422. this._renderParticles(activeMeshes);
  23423. }
  23424. if (this.onBeforeTransparentRendering) {
  23425. this.onBeforeTransparentRendering();
  23426. }
  23427. // Transparent
  23428. if (this._transparentSubMeshes.length !== 0) {
  23429. this._renderTransparent(this._transparentSubMeshes);
  23430. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23431. }
  23432. // Set back stencil to false in case it changes before the edge renderer.
  23433. engine.setStencilBuffer(false);
  23434. // Edges
  23435. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23436. this._edgesRenderers.data[edgesRendererIndex].render();
  23437. }
  23438. // Restore Stencil state.
  23439. engine.setStencilBuffer(stencilState);
  23440. };
  23441. /**
  23442. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23443. * @param subMeshes The submeshes to render
  23444. */
  23445. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23446. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23447. };
  23448. /**
  23449. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23450. * @param subMeshes The submeshes to render
  23451. */
  23452. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23453. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23454. };
  23455. /**
  23456. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23457. * @param subMeshes The submeshes to render
  23458. */
  23459. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23460. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23461. };
  23462. /**
  23463. * Renders the submeshes in a specified order.
  23464. * @param subMeshes The submeshes to sort before render
  23465. * @param sortCompareFn The comparison function use to sort
  23466. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23467. * @param transparent Specifies to activate blending if true
  23468. */
  23469. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23470. var subIndex = 0;
  23471. var subMesh;
  23472. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23473. for (; subIndex < subMeshes.length; subIndex++) {
  23474. subMesh = subMeshes.data[subIndex];
  23475. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23476. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23477. }
  23478. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23479. if (sortCompareFn) {
  23480. sortedArray.sort(sortCompareFn);
  23481. }
  23482. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23483. subMesh = sortedArray[subIndex];
  23484. if (transparent) {
  23485. var material = subMesh.getMaterial();
  23486. if (material && material.needDepthPrePass) {
  23487. var engine = material.getScene().getEngine();
  23488. engine.setColorWrite(false);
  23489. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23490. subMesh.render(false);
  23491. engine.setColorWrite(true);
  23492. }
  23493. }
  23494. subMesh.render(transparent);
  23495. }
  23496. };
  23497. /**
  23498. * Renders the submeshes in the order they were dispatched (no sort applied).
  23499. * @param subMeshes The submeshes to render
  23500. */
  23501. RenderingGroup.renderUnsorted = function (subMeshes) {
  23502. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23503. var submesh = subMeshes.data[subIndex];
  23504. submesh.render(false);
  23505. }
  23506. };
  23507. /**
  23508. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23509. * are rendered back to front if in the same alpha index.
  23510. *
  23511. * @param a The first submesh
  23512. * @param b The second submesh
  23513. * @returns The result of the comparison
  23514. */
  23515. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23516. // Alpha index first
  23517. if (a._alphaIndex > b._alphaIndex) {
  23518. return 1;
  23519. }
  23520. if (a._alphaIndex < b._alphaIndex) {
  23521. return -1;
  23522. }
  23523. // Then distance to camera
  23524. return RenderingGroup.backToFrontSortCompare(a, b);
  23525. };
  23526. /**
  23527. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23528. * are rendered back to front.
  23529. *
  23530. * @param a The first submesh
  23531. * @param b The second submesh
  23532. * @returns The result of the comparison
  23533. */
  23534. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23535. // Then distance to camera
  23536. if (a._distanceToCamera < b._distanceToCamera) {
  23537. return 1;
  23538. }
  23539. if (a._distanceToCamera > b._distanceToCamera) {
  23540. return -1;
  23541. }
  23542. return 0;
  23543. };
  23544. /**
  23545. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23546. * are rendered front to back (prevent overdraw).
  23547. *
  23548. * @param a The first submesh
  23549. * @param b The second submesh
  23550. * @returns The result of the comparison
  23551. */
  23552. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23553. // Then distance to camera
  23554. if (a._distanceToCamera < b._distanceToCamera) {
  23555. return -1;
  23556. }
  23557. if (a._distanceToCamera > b._distanceToCamera) {
  23558. return 1;
  23559. }
  23560. return 0;
  23561. };
  23562. /**
  23563. * Resets the different lists of submeshes to prepare a new frame.
  23564. */
  23565. RenderingGroup.prototype.prepare = function () {
  23566. this._opaqueSubMeshes.reset();
  23567. this._transparentSubMeshes.reset();
  23568. this._alphaTestSubMeshes.reset();
  23569. this._depthOnlySubMeshes.reset();
  23570. this._particleSystems.reset();
  23571. this._spriteManagers.reset();
  23572. this._edgesRenderers.reset();
  23573. };
  23574. RenderingGroup.prototype.dispose = function () {
  23575. this._opaqueSubMeshes.dispose();
  23576. this._transparentSubMeshes.dispose();
  23577. this._alphaTestSubMeshes.dispose();
  23578. this._depthOnlySubMeshes.dispose();
  23579. this._particleSystems.dispose();
  23580. this._spriteManagers.dispose();
  23581. this._edgesRenderers.dispose();
  23582. };
  23583. /**
  23584. * Inserts the submesh in its correct queue depending on its material.
  23585. * @param subMesh The submesh to dispatch
  23586. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23587. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23588. */
  23589. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23590. // Get mesh and materials if not provided
  23591. if (mesh === undefined) {
  23592. mesh = subMesh.getMesh();
  23593. }
  23594. if (material === undefined) {
  23595. material = subMesh.getMaterial();
  23596. }
  23597. if (material === null || material === undefined) {
  23598. return;
  23599. }
  23600. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23601. this._transparentSubMeshes.push(subMesh);
  23602. }
  23603. else if (material.needAlphaTesting()) { // Alpha test
  23604. if (material.needDepthPrePass) {
  23605. this._depthOnlySubMeshes.push(subMesh);
  23606. }
  23607. this._alphaTestSubMeshes.push(subMesh);
  23608. }
  23609. else {
  23610. if (material.needDepthPrePass) {
  23611. this._depthOnlySubMeshes.push(subMesh);
  23612. }
  23613. this._opaqueSubMeshes.push(subMesh); // Opaque
  23614. }
  23615. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23616. this._edgesRenderers.push(mesh._edgesRenderer);
  23617. }
  23618. };
  23619. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23620. this._spriteManagers.push(spriteManager);
  23621. };
  23622. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23623. this._particleSystems.push(particleSystem);
  23624. };
  23625. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23626. if (this._particleSystems.length === 0) {
  23627. return;
  23628. }
  23629. // Particles
  23630. var activeCamera = this._scene.activeCamera;
  23631. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23632. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23633. var particleSystem = this._particleSystems.data[particleIndex];
  23634. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23635. continue;
  23636. }
  23637. var emitter = particleSystem.emitter;
  23638. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23639. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23640. }
  23641. }
  23642. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23643. };
  23644. RenderingGroup.prototype._renderSprites = function () {
  23645. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23646. return;
  23647. }
  23648. // Sprites
  23649. var activeCamera = this._scene.activeCamera;
  23650. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23651. for (var id = 0; id < this._spriteManagers.length; id++) {
  23652. var spriteManager = this._spriteManagers.data[id];
  23653. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23654. spriteManager.render();
  23655. }
  23656. }
  23657. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23658. };
  23659. return RenderingGroup;
  23660. }());
  23661. BABYLON.RenderingGroup = RenderingGroup;
  23662. })(BABYLON || (BABYLON = {}));
  23663. //# sourceMappingURL=babylon.renderingGroup.js.map
  23664. var BABYLON;
  23665. (function (BABYLON) {
  23666. /** @hidden */
  23667. var ClickInfo = /** @class */ (function () {
  23668. function ClickInfo() {
  23669. this._singleClick = false;
  23670. this._doubleClick = false;
  23671. this._hasSwiped = false;
  23672. this._ignore = false;
  23673. }
  23674. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23675. get: function () {
  23676. return this._singleClick;
  23677. },
  23678. set: function (b) {
  23679. this._singleClick = b;
  23680. },
  23681. enumerable: true,
  23682. configurable: true
  23683. });
  23684. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23685. get: function () {
  23686. return this._doubleClick;
  23687. },
  23688. set: function (b) {
  23689. this._doubleClick = b;
  23690. },
  23691. enumerable: true,
  23692. configurable: true
  23693. });
  23694. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23695. get: function () {
  23696. return this._hasSwiped;
  23697. },
  23698. set: function (b) {
  23699. this._hasSwiped = b;
  23700. },
  23701. enumerable: true,
  23702. configurable: true
  23703. });
  23704. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23705. get: function () {
  23706. return this._ignore;
  23707. },
  23708. set: function (b) {
  23709. this._ignore = b;
  23710. },
  23711. enumerable: true,
  23712. configurable: true
  23713. });
  23714. return ClickInfo;
  23715. }());
  23716. /**
  23717. * This class is used by the onRenderingGroupObservable
  23718. */
  23719. var RenderingGroupInfo = /** @class */ (function () {
  23720. function RenderingGroupInfo() {
  23721. }
  23722. /**
  23723. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23724. * This stage will be fired no matter what
  23725. */
  23726. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23727. /**
  23728. * Called before opaque object are rendered.
  23729. * This stage will be fired only if there's 3D Opaque content to render
  23730. */
  23731. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23732. /**
  23733. * Called after the opaque objects are rendered and before the transparent ones
  23734. * This stage will be fired only if there's 3D transparent content to render
  23735. */
  23736. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23737. /**
  23738. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23739. * This stage will be fired no matter what
  23740. */
  23741. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23742. return RenderingGroupInfo;
  23743. }());
  23744. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23745. /**
  23746. * Represents a scene to be rendered by the engine.
  23747. * @see http://doc.babylonjs.com/features/scene
  23748. */
  23749. var Scene = /** @class */ (function () {
  23750. /**
  23751. * Creates a new Scene
  23752. * @param engine defines the engine to use to render this scene
  23753. */
  23754. function Scene(engine) {
  23755. // Members
  23756. /**
  23757. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23758. */
  23759. this.autoClear = true;
  23760. /**
  23761. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23762. */
  23763. this.autoClearDepthAndStencil = true;
  23764. /**
  23765. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23766. */
  23767. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23768. /**
  23769. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23770. */
  23771. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23772. this._forceWireframe = false;
  23773. this._forcePointsCloud = false;
  23774. /**
  23775. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23776. */
  23777. this.forceShowBoundingBoxes = false;
  23778. /**
  23779. * Gets or sets a boolean indicating if animations are enabled
  23780. */
  23781. this.animationsEnabled = true;
  23782. this._animationPropertiesOverride = null;
  23783. /**
  23784. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23785. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23786. */
  23787. this.useConstantAnimationDeltaTime = false;
  23788. /**
  23789. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23790. * Please note that it requires to run a ray cast through the scene on every frame
  23791. */
  23792. this.constantlyUpdateMeshUnderPointer = false;
  23793. /**
  23794. * Defines the HTML cursor to use when hovering over interactive elements
  23795. */
  23796. this.hoverCursor = "pointer";
  23797. /**
  23798. * Defines the HTML default cursor to use (empty by default)
  23799. */
  23800. this.defaultCursor = "";
  23801. /**
  23802. * This is used to call preventDefault() on pointer down
  23803. * in order to block unwanted artifacts like system double clicks
  23804. */
  23805. this.preventDefaultOnPointerDown = true;
  23806. // Metadata
  23807. /**
  23808. * Gets or sets user defined metadata
  23809. */
  23810. this.metadata = null;
  23811. /**
  23812. * Use this array to add regular expressions used to disable offline support for specific urls
  23813. */
  23814. this.disableOfflineSupportExceptionRules = new Array();
  23815. /**
  23816. * An event triggered when the scene is disposed.
  23817. */
  23818. this.onDisposeObservable = new BABYLON.Observable();
  23819. this._onDisposeObserver = null;
  23820. /**
  23821. * An event triggered before rendering the scene (right after animations and physics)
  23822. */
  23823. this.onBeforeRenderObservable = new BABYLON.Observable();
  23824. this._onBeforeRenderObserver = null;
  23825. /**
  23826. * An event triggered after rendering the scene
  23827. */
  23828. this.onAfterRenderObservable = new BABYLON.Observable();
  23829. this._onAfterRenderObserver = null;
  23830. /**
  23831. * An event triggered before animating the scene
  23832. */
  23833. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23834. /**
  23835. * An event triggered after animations processing
  23836. */
  23837. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23838. /**
  23839. * An event triggered before draw calls are ready to be sent
  23840. */
  23841. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23842. /**
  23843. * An event triggered after draw calls have been sent
  23844. */
  23845. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23846. /**
  23847. * An event triggered when physic simulation is about to be run
  23848. */
  23849. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23850. /**
  23851. * An event triggered when physic simulation has been done
  23852. */
  23853. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23854. /**
  23855. * An event triggered when the scene is ready
  23856. */
  23857. this.onReadyObservable = new BABYLON.Observable();
  23858. /**
  23859. * An event triggered before rendering a camera
  23860. */
  23861. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23862. this._onBeforeCameraRenderObserver = null;
  23863. /**
  23864. * An event triggered after rendering a camera
  23865. */
  23866. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23867. this._onAfterCameraRenderObserver = null;
  23868. /**
  23869. * An event triggered when active meshes evaluation is about to start
  23870. */
  23871. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23872. /**
  23873. * An event triggered when active meshes evaluation is done
  23874. */
  23875. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23876. /**
  23877. * An event triggered when particles rendering is about to start
  23878. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23879. */
  23880. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23881. /**
  23882. * An event triggered when particles rendering is done
  23883. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23884. */
  23885. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23886. /**
  23887. * An event triggered when sprites rendering is about to start
  23888. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23889. */
  23890. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23891. /**
  23892. * An event triggered when sprites rendering is done
  23893. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23894. */
  23895. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23896. /**
  23897. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23898. */
  23899. this.onDataLoadedObservable = new BABYLON.Observable();
  23900. /**
  23901. * An event triggered when a camera is created
  23902. */
  23903. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23904. /**
  23905. * An event triggered when a camera is removed
  23906. */
  23907. this.onCameraRemovedObservable = new BABYLON.Observable();
  23908. /**
  23909. * An event triggered when a light is created
  23910. */
  23911. this.onNewLightAddedObservable = new BABYLON.Observable();
  23912. /**
  23913. * An event triggered when a light is removed
  23914. */
  23915. this.onLightRemovedObservable = new BABYLON.Observable();
  23916. /**
  23917. * An event triggered when a geometry is created
  23918. */
  23919. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23920. /**
  23921. * An event triggered when a geometry is removed
  23922. */
  23923. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23924. /**
  23925. * An event triggered when a transform node is created
  23926. */
  23927. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23928. /**
  23929. * An event triggered when a transform node is removed
  23930. */
  23931. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23932. /**
  23933. * An event triggered when a mesh is created
  23934. */
  23935. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23936. /**
  23937. * An event triggered when a mesh is removed
  23938. */
  23939. this.onMeshRemovedObservable = new BABYLON.Observable();
  23940. /**
  23941. * An event triggered when render targets are about to be rendered
  23942. * Can happen multiple times per frame.
  23943. */
  23944. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23945. /**
  23946. * An event triggered when render targets were rendered.
  23947. * Can happen multiple times per frame.
  23948. */
  23949. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23950. /**
  23951. * An event triggered before calculating deterministic simulation step
  23952. */
  23953. this.onBeforeStepObservable = new BABYLON.Observable();
  23954. /**
  23955. * An event triggered after calculating deterministic simulation step
  23956. */
  23957. this.onAfterStepObservable = new BABYLON.Observable();
  23958. /**
  23959. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23960. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23961. * 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)
  23962. */
  23963. this.onRenderingGroupObservable = new BABYLON.Observable();
  23964. // Animations
  23965. /**
  23966. * Gets a list of Animations associated with the scene
  23967. */
  23968. this.animations = [];
  23969. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23970. /**
  23971. * 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).
  23972. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23973. */
  23974. this.onPrePointerObservable = new BABYLON.Observable();
  23975. /**
  23976. * Observable event triggered each time an input event is received from the rendering canvas
  23977. */
  23978. this.onPointerObservable = new BABYLON.Observable();
  23979. this._meshPickProceed = false;
  23980. this._currentPickResult = null;
  23981. this._previousPickResult = null;
  23982. this._totalPointersPressed = 0;
  23983. this._doubleClickOccured = false;
  23984. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23985. this.cameraToUseForPointers = null;
  23986. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23987. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23988. this._startingPointerTime = 0;
  23989. this._previousStartingPointerTime = 0;
  23990. this._pointerCaptures = {};
  23991. // Deterministic lockstep
  23992. this._timeAccumulator = 0;
  23993. this._currentStepId = 0;
  23994. this._currentInternalStep = 0;
  23995. // Keyboard
  23996. /**
  23997. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23998. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23999. */
  24000. this.onPreKeyboardObservable = new BABYLON.Observable();
  24001. /**
  24002. * Observable event triggered each time an keyboard event is received from the hosting window
  24003. */
  24004. this.onKeyboardObservable = new BABYLON.Observable();
  24005. // Coordinates system
  24006. this._useRightHandedSystem = false;
  24007. // Fog
  24008. this._fogEnabled = true;
  24009. this._fogMode = Scene.FOGMODE_NONE;
  24010. /**
  24011. * Gets or sets the fog color to use
  24012. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24013. */
  24014. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24015. /**
  24016. * Gets or sets the fog density to use
  24017. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24018. */
  24019. this.fogDensity = 0.1;
  24020. /**
  24021. * Gets or sets the fog start distance to use
  24022. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24023. */
  24024. this.fogStart = 0;
  24025. /**
  24026. * Gets or sets the fog end distance to use
  24027. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24028. */
  24029. this.fogEnd = 1000.0;
  24030. // Lights
  24031. this._shadowsEnabled = true;
  24032. this._lightsEnabled = true;
  24033. /**
  24034. * All of the lights added to this scene
  24035. * @see http://doc.babylonjs.com/babylon101/lights
  24036. */
  24037. this.lights = new Array();
  24038. // Cameras
  24039. /** All of the cameras added to this scene.
  24040. * @see http://doc.babylonjs.com/babylon101/cameras
  24041. */
  24042. this.cameras = new Array();
  24043. /** All of the active cameras added to this scene. */
  24044. this.activeCameras = new Array();
  24045. // Meshes
  24046. /**
  24047. * All of the tranform nodes added to this scene
  24048. * @see http://doc.babylonjs.com/how_to/transformnode
  24049. */
  24050. this.transformNodes = new Array();
  24051. /**
  24052. * All of the (abstract) meshes added to this scene
  24053. */
  24054. this.meshes = new Array();
  24055. /**
  24056. * All of the animation groups added to this scene
  24057. * @see http://doc.babylonjs.com/how_to/group
  24058. */
  24059. this.animationGroups = new Array();
  24060. // Geometries
  24061. this._geometries = new Array();
  24062. /**
  24063. * All of the materials added to this scene
  24064. * @see http://doc.babylonjs.com/babylon101/materials
  24065. */
  24066. this.materials = new Array();
  24067. /**
  24068. * All of the multi-materials added to this scene
  24069. * @see http://doc.babylonjs.com/how_to/multi_materials
  24070. */
  24071. this.multiMaterials = new Array();
  24072. // Textures
  24073. this._texturesEnabled = true;
  24074. /**
  24075. * All of the textures added to this scene
  24076. */
  24077. this.textures = new Array();
  24078. // Particles
  24079. /**
  24080. * Gets or sets a boolean indicating if particles are enabled on this scene
  24081. */
  24082. this.particlesEnabled = true;
  24083. /**
  24084. * All of the particle systems added to this scene
  24085. * @see http://doc.babylonjs.com/babylon101/particles
  24086. */
  24087. this.particleSystems = new Array();
  24088. // Sprites
  24089. /**
  24090. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24091. */
  24092. this.spritesEnabled = true;
  24093. /**
  24094. * All of the sprite managers added to this scene
  24095. * @see http://doc.babylonjs.com/babylon101/sprites
  24096. */
  24097. this.spriteManagers = new Array();
  24098. /**
  24099. * The list of layers (background and foreground) of the scene
  24100. */
  24101. this.layers = new Array();
  24102. /**
  24103. * The list of effect layers (highlights/glow) added to the scene
  24104. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24105. * @see http://doc.babylonjs.com/how_to/glow_layer
  24106. */
  24107. this.effectLayers = new Array();
  24108. // Skeletons
  24109. this._skeletonsEnabled = true;
  24110. /**
  24111. * The list of skeletons added to the scene
  24112. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24113. */
  24114. this.skeletons = new Array();
  24115. // Morph targets
  24116. /**
  24117. * The list of morph target managers added to the scene
  24118. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24119. */
  24120. this.morphTargetManagers = new Array();
  24121. // Lens flares
  24122. /**
  24123. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24124. */
  24125. this.lensFlaresEnabled = true;
  24126. /**
  24127. * The list of lens flare system added to the scene
  24128. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24129. */
  24130. this.lensFlareSystems = new Array();
  24131. // Collisions
  24132. /**
  24133. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24134. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24135. */
  24136. this.collisionsEnabled = true;
  24137. /**
  24138. * Defines the gravity applied to this scene (used only for collisions)
  24139. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24140. */
  24141. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24142. // Postprocesses
  24143. /**
  24144. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24145. */
  24146. this.postProcessesEnabled = true;
  24147. /**
  24148. * The list of postprocesses added to the scene
  24149. */
  24150. this.postProcesses = new Array();
  24151. // Customs render targets
  24152. /**
  24153. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24154. */
  24155. this.renderTargetsEnabled = true;
  24156. /**
  24157. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24158. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24159. */
  24160. this.dumpNextRenderTargets = false;
  24161. /**
  24162. * The list of user defined render targets added to the scene
  24163. */
  24164. this.customRenderTargets = new Array();
  24165. /**
  24166. * Gets the list of meshes imported to the scene through SceneLoader
  24167. */
  24168. this.importedMeshesFiles = new Array();
  24169. // Probes
  24170. /**
  24171. * Gets or sets a boolean indicating if probes are enabled on this scene
  24172. */
  24173. this.probesEnabled = true;
  24174. /**
  24175. * The list of reflection probes added to the scene
  24176. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24177. */
  24178. this.reflectionProbes = new Array();
  24179. /** @hidden */
  24180. this._actionManagers = new Array();
  24181. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24182. // Procedural textures
  24183. /**
  24184. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24185. */
  24186. this.proceduralTexturesEnabled = true;
  24187. /**
  24188. * The list of procedural textures added to the scene
  24189. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24190. */
  24191. this.proceduralTextures = new Array();
  24192. /**
  24193. * The list of sound tracks added to the scene
  24194. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24195. */
  24196. this.soundTracks = new Array();
  24197. this._audioEnabled = true;
  24198. this._headphone = false;
  24199. // Performance counters
  24200. this._totalVertices = new BABYLON.PerfCounter();
  24201. /** @hidden */
  24202. this._activeIndices = new BABYLON.PerfCounter();
  24203. /** @hidden */
  24204. this._activeParticles = new BABYLON.PerfCounter();
  24205. /** @hidden */
  24206. this._activeBones = new BABYLON.PerfCounter();
  24207. this._animationTime = 0;
  24208. /**
  24209. * Gets or sets a general scale for animation speed
  24210. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24211. */
  24212. this.animationTimeScale = 1;
  24213. this._renderId = 0;
  24214. this._executeWhenReadyTimeoutId = -1;
  24215. this._intermediateRendering = false;
  24216. this._viewUpdateFlag = -1;
  24217. this._projectionUpdateFlag = -1;
  24218. this._alternateViewUpdateFlag = -1;
  24219. this._alternateProjectionUpdateFlag = -1;
  24220. /** @hidden */
  24221. this._toBeDisposed = new BABYLON.SmartArray(256);
  24222. this._activeRequests = new Array();
  24223. this._pendingData = new Array();
  24224. this._isDisposed = false;
  24225. /**
  24226. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24227. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24228. */
  24229. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24230. this._activeMeshes = new BABYLON.SmartArray(256);
  24231. this._processedMaterials = new BABYLON.SmartArray(256);
  24232. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24233. /** @hidden */
  24234. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24235. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24236. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24237. /** @hidden */
  24238. this._activeAnimatables = new Array();
  24239. this._transformMatrix = BABYLON.Matrix.Zero();
  24240. this._useAlternateCameraConfiguration = false;
  24241. this._alternateRendering = false;
  24242. /**
  24243. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24244. * This is useful if there are more lights that the maximum simulteanous authorized
  24245. */
  24246. this.requireLightSorting = false;
  24247. this._depthRenderer = {};
  24248. this._activeMeshesFrozen = false;
  24249. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24250. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24251. this._engine.scenes.push(this);
  24252. this._uid = null;
  24253. this._renderingManager = new BABYLON.RenderingManager(this);
  24254. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24255. if (BABYLON.OutlineRenderer) {
  24256. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24257. }
  24258. if (BABYLON.Tools.IsWindowObjectExist()) {
  24259. this.attachControl();
  24260. }
  24261. //simplification queue
  24262. if (BABYLON.SimplificationQueue) {
  24263. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24264. }
  24265. //collision coordinator initialization. For now legacy per default.
  24266. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24267. // Uniform Buffer
  24268. this._createUbo();
  24269. // Default Image processing definition.
  24270. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24271. }
  24272. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24273. /** The fog is deactivated */
  24274. get: function () {
  24275. return Scene._FOGMODE_NONE;
  24276. },
  24277. enumerable: true,
  24278. configurable: true
  24279. });
  24280. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24281. /** The fog density is following an exponential function */
  24282. get: function () {
  24283. return Scene._FOGMODE_EXP;
  24284. },
  24285. enumerable: true,
  24286. configurable: true
  24287. });
  24288. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24289. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24290. get: function () {
  24291. return Scene._FOGMODE_EXP2;
  24292. },
  24293. enumerable: true,
  24294. configurable: true
  24295. });
  24296. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24297. /** The fog density is following a linear function. */
  24298. get: function () {
  24299. return Scene._FOGMODE_LINEAR;
  24300. },
  24301. enumerable: true,
  24302. configurable: true
  24303. });
  24304. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24305. /**
  24306. * Texture used in all pbr material as the reflection texture.
  24307. * As in the majority of the scene they are the same (exception for multi room and so on),
  24308. * this is easier to reference from here than from all the materials.
  24309. */
  24310. get: function () {
  24311. return this._environmentTexture;
  24312. },
  24313. /**
  24314. * Texture used in all pbr material as the reflection texture.
  24315. * As in the majority of the scene they are the same (exception for multi room and so on),
  24316. * this is easier to set here than in all the materials.
  24317. */
  24318. set: function (value) {
  24319. if (this._environmentTexture === value) {
  24320. return;
  24321. }
  24322. this._environmentTexture = value;
  24323. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24324. },
  24325. enumerable: true,
  24326. configurable: true
  24327. });
  24328. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24329. /**
  24330. * Default image processing configuration used either in the rendering
  24331. * Forward main pass or through the imageProcessingPostProcess if present.
  24332. * As in the majority of the scene they are the same (exception for multi camera),
  24333. * this is easier to reference from here than from all the materials and post process.
  24334. *
  24335. * No setter as we it is a shared configuration, you can set the values instead.
  24336. */
  24337. get: function () {
  24338. return this._imageProcessingConfiguration;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24344. get: function () {
  24345. return this._forceWireframe;
  24346. },
  24347. /**
  24348. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24349. */
  24350. set: function (value) {
  24351. if (this._forceWireframe === value) {
  24352. return;
  24353. }
  24354. this._forceWireframe = value;
  24355. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24361. get: function () {
  24362. return this._forcePointsCloud;
  24363. },
  24364. /**
  24365. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24366. */
  24367. set: function (value) {
  24368. if (this._forcePointsCloud === value) {
  24369. return;
  24370. }
  24371. this._forcePointsCloud = value;
  24372. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24378. /**
  24379. * Gets or sets the animation properties override
  24380. */
  24381. get: function () {
  24382. return this._animationPropertiesOverride;
  24383. },
  24384. set: function (value) {
  24385. this._animationPropertiesOverride = value;
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(Scene.prototype, "onDispose", {
  24391. /** Sets a function to be executed when this scene is disposed. */
  24392. set: function (callback) {
  24393. if (this._onDisposeObserver) {
  24394. this.onDisposeObservable.remove(this._onDisposeObserver);
  24395. }
  24396. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. Object.defineProperty(Scene.prototype, "beforeRender", {
  24402. /** Sets a function to be executed before rendering this scene */
  24403. set: function (callback) {
  24404. if (this._onBeforeRenderObserver) {
  24405. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24406. }
  24407. if (callback) {
  24408. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24409. }
  24410. },
  24411. enumerable: true,
  24412. configurable: true
  24413. });
  24414. Object.defineProperty(Scene.prototype, "afterRender", {
  24415. /** Sets a function to be executed after rendering this scene */
  24416. set: function (callback) {
  24417. if (this._onAfterRenderObserver) {
  24418. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24419. }
  24420. if (callback) {
  24421. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24422. }
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24428. /** Sets a function to be executed before rendering a camera*/
  24429. set: function (callback) {
  24430. if (this._onBeforeCameraRenderObserver) {
  24431. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24432. }
  24433. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24439. /** Sets a function to be executed after rendering a camera*/
  24440. set: function (callback) {
  24441. if (this._onAfterCameraRenderObserver) {
  24442. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24443. }
  24444. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24450. /**
  24451. * Gets the gamepad manager associated with the scene
  24452. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24453. */
  24454. get: function () {
  24455. if (!this._gamepadManager) {
  24456. this._gamepadManager = new BABYLON.GamepadManager(this);
  24457. }
  24458. return this._gamepadManager;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24464. /**
  24465. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24466. */
  24467. get: function () {
  24468. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24474. get: function () {
  24475. return this._useRightHandedSystem;
  24476. },
  24477. /**
  24478. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24479. */
  24480. set: function (value) {
  24481. if (this._useRightHandedSystem === value) {
  24482. return;
  24483. }
  24484. this._useRightHandedSystem = value;
  24485. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. /**
  24491. * Sets the step Id used by deterministic lock step
  24492. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24493. * @param newStepId defines the step Id
  24494. */
  24495. Scene.prototype.setStepId = function (newStepId) {
  24496. this._currentStepId = newStepId;
  24497. };
  24498. ;
  24499. /**
  24500. * Gets the step Id used by deterministic lock step
  24501. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24502. * @returns the step Id
  24503. */
  24504. Scene.prototype.getStepId = function () {
  24505. return this._currentStepId;
  24506. };
  24507. ;
  24508. /**
  24509. * Gets the internal step used by deterministic lock step
  24510. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24511. * @returns the internal step
  24512. */
  24513. Scene.prototype.getInternalStep = function () {
  24514. return this._currentInternalStep;
  24515. };
  24516. ;
  24517. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24518. get: function () {
  24519. return this._fogEnabled;
  24520. },
  24521. /**
  24522. * Gets or sets a boolean indicating if fog is enabled on this scene
  24523. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24524. */
  24525. set: function (value) {
  24526. if (this._fogEnabled === value) {
  24527. return;
  24528. }
  24529. this._fogEnabled = value;
  24530. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "fogMode", {
  24536. get: function () {
  24537. return this._fogMode;
  24538. },
  24539. /**
  24540. * Gets or sets the fog mode to use
  24541. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24542. */
  24543. set: function (value) {
  24544. if (this._fogMode === value) {
  24545. return;
  24546. }
  24547. this._fogMode = value;
  24548. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24554. get: function () {
  24555. return this._shadowsEnabled;
  24556. },
  24557. /**
  24558. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24559. */
  24560. set: function (value) {
  24561. if (this._shadowsEnabled === value) {
  24562. return;
  24563. }
  24564. this._shadowsEnabled = value;
  24565. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24571. get: function () {
  24572. return this._lightsEnabled;
  24573. },
  24574. /**
  24575. * Gets or sets a boolean indicating if lights are enabled on this scene
  24576. */
  24577. set: function (value) {
  24578. if (this._lightsEnabled === value) {
  24579. return;
  24580. }
  24581. this._lightsEnabled = value;
  24582. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24588. /** The default material used on meshes when no material is affected */
  24589. get: function () {
  24590. if (!this._defaultMaterial) {
  24591. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24592. }
  24593. return this._defaultMaterial;
  24594. },
  24595. /** The default material used on meshes when no material is affected */
  24596. set: function (value) {
  24597. this._defaultMaterial = value;
  24598. },
  24599. enumerable: true,
  24600. configurable: true
  24601. });
  24602. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24603. get: function () {
  24604. return this._texturesEnabled;
  24605. },
  24606. /**
  24607. * Gets or sets a boolean indicating if textures are enabled on this scene
  24608. */
  24609. set: function (value) {
  24610. if (this._texturesEnabled === value) {
  24611. return;
  24612. }
  24613. this._texturesEnabled = value;
  24614. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24615. },
  24616. enumerable: true,
  24617. configurable: true
  24618. });
  24619. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24620. get: function () {
  24621. return this._skeletonsEnabled;
  24622. },
  24623. /**
  24624. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24625. */
  24626. set: function (value) {
  24627. if (this._skeletonsEnabled === value) {
  24628. return;
  24629. }
  24630. this._skeletonsEnabled = value;
  24631. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24632. },
  24633. enumerable: true,
  24634. configurable: true
  24635. });
  24636. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24637. /**
  24638. * Gets the postprocess render pipeline manager
  24639. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24640. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24641. */
  24642. get: function () {
  24643. if (!this._postProcessRenderPipelineManager) {
  24644. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24645. }
  24646. return this._postProcessRenderPipelineManager;
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24652. /**
  24653. * Gets the main soundtrack associated with the scene
  24654. */
  24655. get: function () {
  24656. if (!this._mainSoundTrack) {
  24657. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24658. }
  24659. return this._mainSoundTrack;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24665. /** @hidden */
  24666. get: function () {
  24667. return this._alternateRendering;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24673. /**
  24674. * Gets the list of frustum planes (built from the active camera)
  24675. */
  24676. get: function () {
  24677. return this._frustumPlanes;
  24678. },
  24679. enumerable: true,
  24680. configurable: true
  24681. });
  24682. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24683. /**
  24684. * Gets the current geometry buffer associated to the scene.
  24685. */
  24686. get: function () {
  24687. return this._geometryBufferRenderer;
  24688. },
  24689. /**
  24690. * Sets the current geometry buffer for the scene.
  24691. */
  24692. set: function (geometryBufferRenderer) {
  24693. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24694. this._geometryBufferRenderer = geometryBufferRenderer;
  24695. }
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Object.defineProperty(Scene.prototype, "debugLayer", {
  24701. /**
  24702. * Gets the debug layer (aka Inspector) associated with the scene
  24703. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24704. */
  24705. get: function () {
  24706. if (!this._debugLayer) {
  24707. this._debugLayer = new BABYLON.DebugLayer(this);
  24708. }
  24709. return this._debugLayer;
  24710. },
  24711. enumerable: true,
  24712. configurable: true
  24713. });
  24714. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24715. /**
  24716. * Gets a boolean indicating if collisions are processed on a web worker
  24717. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24718. */
  24719. get: function () {
  24720. return this._workerCollisions;
  24721. },
  24722. set: function (enabled) {
  24723. if (!BABYLON.CollisionCoordinatorLegacy) {
  24724. return;
  24725. }
  24726. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24727. this._workerCollisions = enabled;
  24728. if (this.collisionCoordinator) {
  24729. this.collisionCoordinator.destroy();
  24730. }
  24731. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24732. this.collisionCoordinator.init(this);
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24738. /**
  24739. * Gets the octree used to boost mesh selection (picking)
  24740. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24741. */
  24742. get: function () {
  24743. return this._selectionOctree;
  24744. },
  24745. enumerable: true,
  24746. configurable: true
  24747. });
  24748. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24749. /**
  24750. * Gets the mesh that is currently under the pointer
  24751. */
  24752. get: function () {
  24753. return this._pointerOverMesh;
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. Object.defineProperty(Scene.prototype, "pointerX", {
  24759. /**
  24760. * Gets the current on-screen X position of the pointer
  24761. */
  24762. get: function () {
  24763. return this._pointerX;
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. Object.defineProperty(Scene.prototype, "pointerY", {
  24769. /**
  24770. * Gets the current on-screen Y position of the pointer
  24771. */
  24772. get: function () {
  24773. return this._pointerY;
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. /**
  24779. * Gets the cached material (ie. the latest rendered one)
  24780. * @returns the cached material
  24781. */
  24782. Scene.prototype.getCachedMaterial = function () {
  24783. return this._cachedMaterial;
  24784. };
  24785. /**
  24786. * Gets the cached effect (ie. the latest rendered one)
  24787. * @returns the cached effect
  24788. */
  24789. Scene.prototype.getCachedEffect = function () {
  24790. return this._cachedEffect;
  24791. };
  24792. /**
  24793. * Gets the cached visibility state (ie. the latest rendered one)
  24794. * @returns the cached visibility state
  24795. */
  24796. Scene.prototype.getCachedVisibility = function () {
  24797. return this._cachedVisibility;
  24798. };
  24799. /**
  24800. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24801. * @param material defines the current material
  24802. * @param effect defines the current effect
  24803. * @param visibility defines the current visibility state
  24804. * @returns true if one parameter is not cached
  24805. */
  24806. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24807. if (visibility === void 0) { visibility = 1; }
  24808. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24809. };
  24810. /**
  24811. * Gets the bounding box renderer associated with the scene
  24812. * @returns a BoundingBoxRenderer
  24813. */
  24814. Scene.prototype.getBoundingBoxRenderer = function () {
  24815. if (!this._boundingBoxRenderer) {
  24816. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24817. }
  24818. return this._boundingBoxRenderer;
  24819. };
  24820. /**
  24821. * Gets the outline renderer associated with the scene
  24822. * @returns a OutlineRenderer
  24823. */
  24824. Scene.prototype.getOutlineRenderer = function () {
  24825. return this._outlineRenderer;
  24826. };
  24827. /**
  24828. * Gets the engine associated with the scene
  24829. * @returns an Engine
  24830. */
  24831. Scene.prototype.getEngine = function () {
  24832. return this._engine;
  24833. };
  24834. /**
  24835. * Gets the total number of vertices rendered per frame
  24836. * @returns the total number of vertices rendered per frame
  24837. */
  24838. Scene.prototype.getTotalVertices = function () {
  24839. return this._totalVertices.current;
  24840. };
  24841. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24842. /**
  24843. * Gets the performance counter for total vertices
  24844. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24845. */
  24846. get: function () {
  24847. return this._totalVertices;
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. /**
  24853. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24854. * @returns the total number of active indices rendered per frame
  24855. */
  24856. Scene.prototype.getActiveIndices = function () {
  24857. return this._activeIndices.current;
  24858. };
  24859. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24860. /**
  24861. * Gets the performance counter for active indices
  24862. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24863. */
  24864. get: function () {
  24865. return this._activeIndices;
  24866. },
  24867. enumerable: true,
  24868. configurable: true
  24869. });
  24870. /**
  24871. * Gets the total number of active particles rendered per frame
  24872. * @returns the total number of active particles rendered per frame
  24873. */
  24874. Scene.prototype.getActiveParticles = function () {
  24875. return this._activeParticles.current;
  24876. };
  24877. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24878. /**
  24879. * Gets the performance counter for active particles
  24880. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24881. */
  24882. get: function () {
  24883. return this._activeParticles;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. /**
  24889. * Gets the total number of active bones rendered per frame
  24890. * @returns the total number of active bones rendered per frame
  24891. */
  24892. Scene.prototype.getActiveBones = function () {
  24893. return this._activeBones.current;
  24894. };
  24895. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24896. /**
  24897. * Gets the performance counter for active bones
  24898. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24899. */
  24900. get: function () {
  24901. return this._activeBones;
  24902. },
  24903. enumerable: true,
  24904. configurable: true
  24905. });
  24906. /** @hidden */
  24907. Scene.prototype.getInterFramePerfCounter = function () {
  24908. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24909. return 0;
  24910. };
  24911. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24912. /** @hidden */
  24913. get: function () {
  24914. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24915. return null;
  24916. },
  24917. enumerable: true,
  24918. configurable: true
  24919. });
  24920. /** @hidden */
  24921. Scene.prototype.getLastFrameDuration = function () {
  24922. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24923. return 0;
  24924. };
  24925. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24926. /** @hidden */
  24927. get: function () {
  24928. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24929. return null;
  24930. },
  24931. enumerable: true,
  24932. configurable: true
  24933. });
  24934. /** @hidden */
  24935. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24936. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24937. return 0;
  24938. };
  24939. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24940. /** @hidden */
  24941. get: function () {
  24942. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24943. return null;
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. /**
  24949. * Gets the array of active meshes
  24950. * @returns an array of AbstractMesh
  24951. */
  24952. Scene.prototype.getActiveMeshes = function () {
  24953. return this._activeMeshes;
  24954. };
  24955. /** @hidden */
  24956. Scene.prototype.getRenderTargetsDuration = function () {
  24957. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24958. return 0;
  24959. };
  24960. /** @hidden */
  24961. Scene.prototype.getRenderDuration = function () {
  24962. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24963. return 0;
  24964. };
  24965. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24966. /** @hidden */
  24967. get: function () {
  24968. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24969. return null;
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. /** @hidden */
  24975. Scene.prototype.getParticlesDuration = function () {
  24976. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24977. return 0;
  24978. };
  24979. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24980. /** @hidden */
  24981. get: function () {
  24982. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24983. return null;
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. /** @hidden */
  24989. Scene.prototype.getSpritesDuration = function () {
  24990. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24991. return 0;
  24992. };
  24993. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24994. /** @hidden */
  24995. get: function () {
  24996. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24997. return null;
  24998. },
  24999. enumerable: true,
  25000. configurable: true
  25001. });
  25002. /**
  25003. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25004. * @returns a number
  25005. */
  25006. Scene.prototype.getAnimationRatio = function () {
  25007. return this._animationRatio;
  25008. };
  25009. /**
  25010. * Gets an unique Id for the current frame
  25011. * @returns a number
  25012. */
  25013. Scene.prototype.getRenderId = function () {
  25014. return this._renderId;
  25015. };
  25016. /** Call this function if you want to manually increment the render Id*/
  25017. Scene.prototype.incrementRenderId = function () {
  25018. this._renderId++;
  25019. };
  25020. Scene.prototype._updatePointerPosition = function (evt) {
  25021. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25022. if (!canvasRect) {
  25023. return;
  25024. }
  25025. this._pointerX = evt.clientX - canvasRect.left;
  25026. this._pointerY = evt.clientY - canvasRect.top;
  25027. this._unTranslatedPointerX = this._pointerX;
  25028. this._unTranslatedPointerY = this._pointerY;
  25029. };
  25030. Scene.prototype._createUbo = function () {
  25031. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25032. this._sceneUbo.addUniform("viewProjection", 16);
  25033. this._sceneUbo.addUniform("view", 16);
  25034. };
  25035. Scene.prototype._createAlternateUbo = function () {
  25036. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25037. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25038. this._alternateSceneUbo.addUniform("view", 16);
  25039. };
  25040. // Pointers handling
  25041. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25042. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25043. if (result) {
  25044. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25045. }
  25046. return result;
  25047. };
  25048. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25049. if (pointerInfo.pickInfo) {
  25050. if (!pointerInfo.pickInfo.ray) {
  25051. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25052. }
  25053. }
  25054. };
  25055. /**
  25056. * Use this method to simulate a pointer move on a mesh
  25057. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25058. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25059. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25060. * @returns the current scene
  25061. */
  25062. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25063. var evt = new PointerEvent("pointermove", pointerEventInit);
  25064. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25065. return this;
  25066. }
  25067. return this._processPointerMove(pickResult, evt);
  25068. };
  25069. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25070. var canvas = this._engine.getRenderingCanvas();
  25071. if (!canvas) {
  25072. return this;
  25073. }
  25074. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25075. this.setPointerOverSprite(null);
  25076. this.setPointerOverMesh(pickResult.pickedMesh);
  25077. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25078. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25079. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25080. }
  25081. else {
  25082. canvas.style.cursor = this.hoverCursor;
  25083. }
  25084. }
  25085. else {
  25086. canvas.style.cursor = this.defaultCursor;
  25087. }
  25088. }
  25089. else {
  25090. this.setPointerOverMesh(null);
  25091. // Sprites
  25092. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25093. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25094. this.setPointerOverSprite(pickResult.pickedSprite);
  25095. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25096. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25097. }
  25098. else {
  25099. canvas.style.cursor = this.hoverCursor;
  25100. }
  25101. }
  25102. else {
  25103. this.setPointerOverSprite(null);
  25104. // Restore pointer
  25105. canvas.style.cursor = this.defaultCursor;
  25106. }
  25107. }
  25108. if (pickResult) {
  25109. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25110. if (this.onPointerMove) {
  25111. this.onPointerMove(evt, pickResult, type);
  25112. }
  25113. if (this.onPointerObservable.hasObservers()) {
  25114. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25115. this._setRayOnPointerInfo(pi);
  25116. this.onPointerObservable.notifyObservers(pi, type);
  25117. }
  25118. }
  25119. return this;
  25120. };
  25121. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25122. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25123. if (pickResult) {
  25124. pi.ray = pickResult.ray;
  25125. }
  25126. this.onPrePointerObservable.notifyObservers(pi, type);
  25127. if (pi.skipOnPointerObservable) {
  25128. return true;
  25129. }
  25130. else {
  25131. return false;
  25132. }
  25133. };
  25134. /**
  25135. * Use this method to simulate a pointer down on a mesh
  25136. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25137. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25138. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25139. * @returns the current scene
  25140. */
  25141. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25142. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25143. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25144. return this;
  25145. }
  25146. return this._processPointerDown(pickResult, evt);
  25147. };
  25148. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25149. var _this = this;
  25150. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25151. this._pickedDownMesh = pickResult.pickedMesh;
  25152. var actionManager = pickResult.pickedMesh.actionManager;
  25153. if (actionManager) {
  25154. if (actionManager.hasPickTriggers) {
  25155. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25156. switch (evt.button) {
  25157. case 0:
  25158. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25159. break;
  25160. case 1:
  25161. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25162. break;
  25163. case 2:
  25164. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25165. break;
  25166. }
  25167. }
  25168. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25169. window.setTimeout(function () {
  25170. 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);
  25171. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25172. if (_this._totalPointersPressed !== 0 &&
  25173. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25174. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25175. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25176. _this._startingPointerTime = 0;
  25177. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25178. }
  25179. }
  25180. }, Scene.LongPressDelay);
  25181. }
  25182. }
  25183. }
  25184. if (pickResult) {
  25185. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25186. if (this.onPointerDown) {
  25187. this.onPointerDown(evt, pickResult, type);
  25188. }
  25189. if (this.onPointerObservable.hasObservers()) {
  25190. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25191. this._setRayOnPointerInfo(pi);
  25192. this.onPointerObservable.notifyObservers(pi, type);
  25193. }
  25194. }
  25195. return this;
  25196. };
  25197. /**
  25198. * Use this method to simulate a pointer up on a mesh
  25199. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25200. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25201. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25202. * @returns the current scene
  25203. */
  25204. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25205. var evt = new PointerEvent("pointerup", pointerEventInit);
  25206. var clickInfo = new ClickInfo();
  25207. clickInfo.singleClick = true;
  25208. clickInfo.ignore = true;
  25209. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25210. return this;
  25211. }
  25212. return this._processPointerUp(pickResult, evt, clickInfo);
  25213. };
  25214. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25215. if (pickResult && pickResult && pickResult.pickedMesh) {
  25216. this._pickedUpMesh = pickResult.pickedMesh;
  25217. if (this._pickedDownMesh === this._pickedUpMesh) {
  25218. if (this.onPointerPick) {
  25219. this.onPointerPick(evt, pickResult);
  25220. }
  25221. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25222. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25223. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25224. this._setRayOnPointerInfo(pi);
  25225. this.onPointerObservable.notifyObservers(pi, type_1);
  25226. }
  25227. }
  25228. if (pickResult.pickedMesh.actionManager) {
  25229. if (clickInfo.ignore) {
  25230. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25231. }
  25232. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25233. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25234. }
  25235. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25236. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25237. }
  25238. }
  25239. }
  25240. if (this._pickedDownMesh &&
  25241. this._pickedDownMesh.actionManager &&
  25242. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25243. this._pickedDownMesh !== this._pickedUpMesh) {
  25244. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25245. }
  25246. var type = BABYLON.PointerEventTypes.POINTERUP;
  25247. if (this.onPointerObservable.hasObservers()) {
  25248. if (!clickInfo.ignore) {
  25249. if (!clickInfo.hasSwiped) {
  25250. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25251. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25252. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25253. this._setRayOnPointerInfo(pi);
  25254. this.onPointerObservable.notifyObservers(pi, type_2);
  25255. }
  25256. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25257. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25258. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25259. this._setRayOnPointerInfo(pi);
  25260. this.onPointerObservable.notifyObservers(pi, type_3);
  25261. }
  25262. }
  25263. }
  25264. else {
  25265. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25266. this._setRayOnPointerInfo(pi);
  25267. this.onPointerObservable.notifyObservers(pi, type);
  25268. }
  25269. }
  25270. if (this.onPointerUp) {
  25271. this.onPointerUp(evt, pickResult, type);
  25272. }
  25273. return this;
  25274. };
  25275. /**
  25276. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25277. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25278. * @returns true if the pointer was captured
  25279. */
  25280. Scene.prototype.isPointerCaptured = function (pointerId) {
  25281. if (pointerId === void 0) { pointerId = 0; }
  25282. return this._pointerCaptures[pointerId];
  25283. };
  25284. /**
  25285. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25286. * @param attachUp defines if you want to attach events to pointerup
  25287. * @param attachDown defines if you want to attach events to pointerdown
  25288. * @param attachMove defines if you want to attach events to pointermove
  25289. */
  25290. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25291. var _this = this;
  25292. if (attachUp === void 0) { attachUp = true; }
  25293. if (attachDown === void 0) { attachDown = true; }
  25294. if (attachMove === void 0) { attachMove = true; }
  25295. this._initActionManager = function (act, clickInfo) {
  25296. if (!_this._meshPickProceed) {
  25297. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25298. _this._currentPickResult = pickResult;
  25299. if (pickResult) {
  25300. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25301. }
  25302. _this._meshPickProceed = true;
  25303. }
  25304. return act;
  25305. };
  25306. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25307. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25308. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25309. btn !== _this._previousButtonPressed) {
  25310. _this._doubleClickOccured = false;
  25311. clickInfo.singleClick = true;
  25312. clickInfo.ignore = false;
  25313. cb(clickInfo, _this._currentPickResult);
  25314. }
  25315. };
  25316. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25317. var clickInfo = new ClickInfo();
  25318. _this._currentPickResult = null;
  25319. var act = null;
  25320. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25321. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25322. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25323. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25324. act = _this._initActionManager(act, clickInfo);
  25325. if (act)
  25326. checkPicking = act.hasPickTriggers;
  25327. }
  25328. if (checkPicking) {
  25329. var btn = evt.button;
  25330. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25331. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25332. if (!clickInfo.hasSwiped) {
  25333. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25334. if (!checkSingleClickImmediately) {
  25335. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25336. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25337. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25338. act = _this._initActionManager(act, clickInfo);
  25339. if (act)
  25340. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25341. }
  25342. }
  25343. if (checkSingleClickImmediately) {
  25344. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25345. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25346. btn !== _this._previousButtonPressed) {
  25347. clickInfo.singleClick = true;
  25348. cb(clickInfo, _this._currentPickResult);
  25349. }
  25350. }
  25351. // at least one double click is required to be check and exclusive double click is enabled
  25352. else {
  25353. // wait that no double click has been raised during the double click delay
  25354. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25355. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25356. }
  25357. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25358. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25359. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25360. act = _this._initActionManager(act, clickInfo);
  25361. if (act)
  25362. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25363. }
  25364. if (checkDoubleClick) {
  25365. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25366. if (btn === _this._previousButtonPressed &&
  25367. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25368. !_this._doubleClickOccured) {
  25369. // pointer has not moved for 2 clicks, it's a double click
  25370. if (!clickInfo.hasSwiped &&
  25371. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25372. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25373. _this._previousStartingPointerTime = 0;
  25374. _this._doubleClickOccured = true;
  25375. clickInfo.doubleClick = true;
  25376. clickInfo.ignore = false;
  25377. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25378. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25379. }
  25380. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25381. cb(clickInfo, _this._currentPickResult);
  25382. }
  25383. // if the two successive clicks are too far, it's just two simple clicks
  25384. else {
  25385. _this._doubleClickOccured = false;
  25386. _this._previousStartingPointerTime = _this._startingPointerTime;
  25387. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25388. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25389. _this._previousButtonPressed = btn;
  25390. if (Scene.ExclusiveDoubleClickMode) {
  25391. if (_this._previousDelayedSimpleClickTimeout) {
  25392. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25393. }
  25394. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25395. cb(clickInfo, _this._previousPickResult);
  25396. }
  25397. else {
  25398. cb(clickInfo, _this._currentPickResult);
  25399. }
  25400. }
  25401. }
  25402. // just the first click of the double has been raised
  25403. else {
  25404. _this._doubleClickOccured = false;
  25405. _this._previousStartingPointerTime = _this._startingPointerTime;
  25406. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25407. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25408. _this._previousButtonPressed = btn;
  25409. }
  25410. }
  25411. }
  25412. }
  25413. clickInfo.ignore = true;
  25414. cb(clickInfo, _this._currentPickResult);
  25415. };
  25416. this._spritePredicate = function (sprite) {
  25417. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25418. };
  25419. this._onPointerMove = function (evt) {
  25420. _this._updatePointerPosition(evt);
  25421. // PreObservable support
  25422. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25423. return;
  25424. }
  25425. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25426. return;
  25427. }
  25428. if (!_this.pointerMovePredicate) {
  25429. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25430. }
  25431. // Meshes
  25432. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25433. _this._processPointerMove(pickResult, evt);
  25434. };
  25435. this._onPointerDown = function (evt) {
  25436. _this._totalPointersPressed++;
  25437. _this._pickedDownMesh = null;
  25438. _this._meshPickProceed = false;
  25439. _this._updatePointerPosition(evt);
  25440. if (_this.preventDefaultOnPointerDown && canvas) {
  25441. evt.preventDefault();
  25442. canvas.focus();
  25443. }
  25444. // PreObservable support
  25445. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25446. return;
  25447. }
  25448. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25449. return;
  25450. }
  25451. _this._pointerCaptures[evt.pointerId] = true;
  25452. _this._startingPointerPosition.x = _this._pointerX;
  25453. _this._startingPointerPosition.y = _this._pointerY;
  25454. _this._startingPointerTime = Date.now();
  25455. if (!_this.pointerDownPredicate) {
  25456. _this.pointerDownPredicate = function (mesh) {
  25457. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25458. };
  25459. }
  25460. // Meshes
  25461. _this._pickedDownMesh = null;
  25462. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25463. _this._processPointerDown(pickResult, evt);
  25464. // Sprites
  25465. _this._pickedDownSprite = null;
  25466. if (_this.spriteManagers.length > 0) {
  25467. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25468. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25469. if (pickResult.pickedSprite.actionManager) {
  25470. _this._pickedDownSprite = pickResult.pickedSprite;
  25471. switch (evt.button) {
  25472. case 0:
  25473. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25474. break;
  25475. case 1:
  25476. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25477. break;
  25478. case 2:
  25479. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25480. break;
  25481. }
  25482. if (pickResult.pickedSprite.actionManager) {
  25483. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25484. }
  25485. }
  25486. }
  25487. }
  25488. };
  25489. this._onPointerUp = function (evt) {
  25490. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25491. return; // So we need to test it the pointer down was pressed before.
  25492. }
  25493. _this._totalPointersPressed--;
  25494. _this._pickedUpMesh = null;
  25495. _this._meshPickProceed = false;
  25496. _this._updatePointerPosition(evt);
  25497. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25498. // PreObservable support
  25499. if (_this.onPrePointerObservable.hasObservers()) {
  25500. if (!clickInfo.ignore) {
  25501. if (!clickInfo.hasSwiped) {
  25502. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25503. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25504. return;
  25505. }
  25506. }
  25507. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25508. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25509. return;
  25510. }
  25511. }
  25512. }
  25513. }
  25514. else {
  25515. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25516. return;
  25517. }
  25518. }
  25519. }
  25520. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25521. return;
  25522. }
  25523. _this._pointerCaptures[evt.pointerId] = false;
  25524. if (!_this.pointerUpPredicate) {
  25525. _this.pointerUpPredicate = function (mesh) {
  25526. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25527. };
  25528. }
  25529. // Meshes
  25530. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25531. _this._initActionManager(null, clickInfo);
  25532. }
  25533. if (!pickResult) {
  25534. pickResult = _this._currentPickResult;
  25535. }
  25536. _this._processPointerUp(pickResult, evt, clickInfo);
  25537. // Sprites
  25538. if (!clickInfo.ignore) {
  25539. if (_this.spriteManagers.length > 0) {
  25540. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25541. if (spritePickResult) {
  25542. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25543. if (spritePickResult.pickedSprite.actionManager) {
  25544. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25545. if (spritePickResult.pickedSprite.actionManager) {
  25546. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25547. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25548. }
  25549. }
  25550. }
  25551. }
  25552. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25553. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25554. }
  25555. }
  25556. }
  25557. }
  25558. _this._previousPickResult = _this._currentPickResult;
  25559. });
  25560. };
  25561. this._onKeyDown = function (evt) {
  25562. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25563. if (_this.onPreKeyboardObservable.hasObservers()) {
  25564. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25565. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25566. if (pi.skipOnPointerObservable) {
  25567. return;
  25568. }
  25569. }
  25570. if (_this.onKeyboardObservable.hasObservers()) {
  25571. var pi = new BABYLON.KeyboardInfo(type, evt);
  25572. _this.onKeyboardObservable.notifyObservers(pi, type);
  25573. }
  25574. if (_this.actionManager) {
  25575. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25576. }
  25577. };
  25578. this._onKeyUp = function (evt) {
  25579. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25580. if (_this.onPreKeyboardObservable.hasObservers()) {
  25581. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25582. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25583. if (pi.skipOnPointerObservable) {
  25584. return;
  25585. }
  25586. }
  25587. if (_this.onKeyboardObservable.hasObservers()) {
  25588. var pi = new BABYLON.KeyboardInfo(type, evt);
  25589. _this.onKeyboardObservable.notifyObservers(pi, type);
  25590. }
  25591. if (_this.actionManager) {
  25592. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25593. }
  25594. };
  25595. var engine = this.getEngine();
  25596. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25597. if (!canvas) {
  25598. return;
  25599. }
  25600. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25601. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25602. });
  25603. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25604. if (!canvas) {
  25605. return;
  25606. }
  25607. canvas.removeEventListener("keydown", _this._onKeyDown);
  25608. canvas.removeEventListener("keyup", _this._onKeyUp);
  25609. });
  25610. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25611. var canvas = this._engine.getRenderingCanvas();
  25612. if (!canvas) {
  25613. return;
  25614. }
  25615. if (attachMove) {
  25616. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25617. // Wheel
  25618. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25619. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25620. }
  25621. if (attachDown) {
  25622. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25623. }
  25624. if (attachUp) {
  25625. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25626. }
  25627. canvas.tabIndex = 1;
  25628. };
  25629. /** Detaches all event handlers*/
  25630. Scene.prototype.detachControl = function () {
  25631. var engine = this.getEngine();
  25632. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25633. var canvas = engine.getRenderingCanvas();
  25634. if (!canvas) {
  25635. return;
  25636. }
  25637. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25638. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25639. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25640. if (this._onCanvasBlurObserver) {
  25641. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25642. }
  25643. if (this._onCanvasFocusObserver) {
  25644. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25645. }
  25646. // Wheel
  25647. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25648. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25649. // Keyboard
  25650. canvas.removeEventListener("keydown", this._onKeyDown);
  25651. canvas.removeEventListener("keyup", this._onKeyUp);
  25652. // Observables
  25653. this.onKeyboardObservable.clear();
  25654. this.onPreKeyboardObservable.clear();
  25655. this.onPointerObservable.clear();
  25656. this.onPrePointerObservable.clear();
  25657. };
  25658. /**
  25659. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25660. * Delay loaded resources are not taking in account
  25661. * @return true if all required resources are ready
  25662. */
  25663. Scene.prototype.isReady = function () {
  25664. if (this._isDisposed) {
  25665. return false;
  25666. }
  25667. if (this._pendingData.length > 0) {
  25668. return false;
  25669. }
  25670. var index;
  25671. var engine = this.getEngine();
  25672. // Geometries
  25673. for (index = 0; index < this._geometries.length; index++) {
  25674. var geometry = this._geometries[index];
  25675. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25676. return false;
  25677. }
  25678. }
  25679. // Meshes
  25680. for (index = 0; index < this.meshes.length; index++) {
  25681. var mesh = this.meshes[index];
  25682. if (!mesh.isEnabled()) {
  25683. continue;
  25684. }
  25685. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25686. continue;
  25687. }
  25688. if (!mesh.isReady(true)) {
  25689. return false;
  25690. }
  25691. // Effect layers
  25692. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25693. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25694. var layer = _a[_i];
  25695. if (!layer.hasMesh(mesh)) {
  25696. continue;
  25697. }
  25698. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25699. var subMesh = _c[_b];
  25700. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25701. return false;
  25702. }
  25703. }
  25704. }
  25705. }
  25706. // Post-processes
  25707. if (this.activeCameras && this.activeCameras.length > 0) {
  25708. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25709. var camera = _e[_d];
  25710. if (!camera.isReady(true)) {
  25711. return false;
  25712. }
  25713. }
  25714. }
  25715. else if (this.activeCamera) {
  25716. if (!this.activeCamera.isReady(true)) {
  25717. return false;
  25718. }
  25719. }
  25720. // Particles
  25721. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25722. var particleSystem = _g[_f];
  25723. if (!particleSystem.isReady()) {
  25724. return false;
  25725. }
  25726. }
  25727. return true;
  25728. };
  25729. /** Resets all cached information relative to material (including effect and visibility) */
  25730. Scene.prototype.resetCachedMaterial = function () {
  25731. this._cachedMaterial = null;
  25732. this._cachedEffect = null;
  25733. this._cachedVisibility = null;
  25734. };
  25735. /**
  25736. * Registers a function to be called before every frame render
  25737. * @param func defines the function to register
  25738. */
  25739. Scene.prototype.registerBeforeRender = function (func) {
  25740. this.onBeforeRenderObservable.add(func);
  25741. };
  25742. /**
  25743. * Unregisters a function called before every frame render
  25744. * @param func defines the function to unregister
  25745. */
  25746. Scene.prototype.unregisterBeforeRender = function (func) {
  25747. this.onBeforeRenderObservable.removeCallback(func);
  25748. };
  25749. /**
  25750. * Registers a function to be called after every frame render
  25751. * @param func defines the function to register
  25752. */
  25753. Scene.prototype.registerAfterRender = function (func) {
  25754. this.onAfterRenderObservable.add(func);
  25755. };
  25756. /**
  25757. * Unregisters a function called after every frame render
  25758. * @param func defines the function to unregister
  25759. */
  25760. Scene.prototype.unregisterAfterRender = function (func) {
  25761. this.onAfterRenderObservable.removeCallback(func);
  25762. };
  25763. Scene.prototype._executeOnceBeforeRender = function (func) {
  25764. var _this = this;
  25765. var execFunc = function () {
  25766. func();
  25767. setTimeout(function () {
  25768. _this.unregisterBeforeRender(execFunc);
  25769. });
  25770. };
  25771. this.registerBeforeRender(execFunc);
  25772. };
  25773. /**
  25774. * The provided function will run before render once and will be disposed afterwards.
  25775. * A timeout delay can be provided so that the function will be executed in N ms.
  25776. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25777. * @param func The function to be executed.
  25778. * @param timeout optional delay in ms
  25779. */
  25780. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25781. var _this = this;
  25782. if (timeout !== undefined) {
  25783. setTimeout(function () {
  25784. _this._executeOnceBeforeRender(func);
  25785. }, timeout);
  25786. }
  25787. else {
  25788. this._executeOnceBeforeRender(func);
  25789. }
  25790. };
  25791. /** @hidden */
  25792. Scene.prototype._addPendingData = function (data) {
  25793. this._pendingData.push(data);
  25794. };
  25795. /** @hidden */
  25796. Scene.prototype._removePendingData = function (data) {
  25797. var wasLoading = this.isLoading;
  25798. var index = this._pendingData.indexOf(data);
  25799. if (index !== -1) {
  25800. this._pendingData.splice(index, 1);
  25801. }
  25802. if (wasLoading && !this.isLoading) {
  25803. this.onDataLoadedObservable.notifyObservers(this);
  25804. }
  25805. };
  25806. /**
  25807. * Returns the number of items waiting to be loaded
  25808. * @returns the number of items waiting to be loaded
  25809. */
  25810. Scene.prototype.getWaitingItemsCount = function () {
  25811. return this._pendingData.length;
  25812. };
  25813. Object.defineProperty(Scene.prototype, "isLoading", {
  25814. /**
  25815. * Returns a boolean indicating if the scene is still loading data
  25816. */
  25817. get: function () {
  25818. return this._pendingData.length > 0;
  25819. },
  25820. enumerable: true,
  25821. configurable: true
  25822. });
  25823. /**
  25824. * Registers a function to be executed when the scene is ready
  25825. * @param {Function} func - the function to be executed
  25826. */
  25827. Scene.prototype.executeWhenReady = function (func) {
  25828. var _this = this;
  25829. this.onReadyObservable.add(func);
  25830. if (this._executeWhenReadyTimeoutId !== -1) {
  25831. return;
  25832. }
  25833. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25834. _this._checkIsReady();
  25835. }, 150);
  25836. };
  25837. /**
  25838. * Returns a promise that resolves when the scene is ready
  25839. * @returns A promise that resolves when the scene is ready
  25840. */
  25841. Scene.prototype.whenReadyAsync = function () {
  25842. var _this = this;
  25843. return new Promise(function (resolve) {
  25844. _this.executeWhenReady(function () {
  25845. resolve();
  25846. });
  25847. });
  25848. };
  25849. /** @hidden */
  25850. Scene.prototype._checkIsReady = function () {
  25851. var _this = this;
  25852. if (this.isReady()) {
  25853. this.onReadyObservable.notifyObservers(this);
  25854. this.onReadyObservable.clear();
  25855. this._executeWhenReadyTimeoutId = -1;
  25856. return;
  25857. }
  25858. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25859. _this._checkIsReady();
  25860. }, 150);
  25861. };
  25862. // Animations
  25863. /**
  25864. * Will start the animation sequence of a given target
  25865. * @param target defines the target
  25866. * @param from defines from which frame should animation start
  25867. * @param to defines until which frame should animation run.
  25868. * @param weight defines the weight to apply to the animation (1.0 by default)
  25869. * @param loop defines if the animation loops
  25870. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25871. * @param onAnimationEnd defines the function to be executed when the animation ends
  25872. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25873. * @returns the animatable object created for this animation
  25874. */
  25875. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25876. if (weight === void 0) { weight = 1.0; }
  25877. if (speedRatio === void 0) { speedRatio = 1.0; }
  25878. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25879. returnedAnimatable.weight = weight;
  25880. return returnedAnimatable;
  25881. };
  25882. /**
  25883. * Will start the animation sequence of a given target
  25884. * @param target defines the target
  25885. * @param from defines from which frame should animation start
  25886. * @param to defines until which frame should animation run.
  25887. * @param loop defines if the animation loops
  25888. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25889. * @param onAnimationEnd defines the function to be executed when the animation ends
  25890. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25891. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25892. * @returns the animatable object created for this animation
  25893. */
  25894. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25895. if (speedRatio === void 0) { speedRatio = 1.0; }
  25896. if (stopCurrent === void 0) { stopCurrent = true; }
  25897. if (from > to && speedRatio > 0) {
  25898. speedRatio *= -1;
  25899. }
  25900. if (stopCurrent) {
  25901. this.stopAnimation(target);
  25902. }
  25903. if (!animatable) {
  25904. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25905. }
  25906. // Local animations
  25907. if (target.animations) {
  25908. animatable.appendAnimations(target, target.animations);
  25909. }
  25910. // Children animations
  25911. if (target.getAnimatables) {
  25912. var animatables = target.getAnimatables();
  25913. for (var index = 0; index < animatables.length; index++) {
  25914. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25915. }
  25916. }
  25917. animatable.reset();
  25918. return animatable;
  25919. };
  25920. /**
  25921. * Begin a new animation on a given node
  25922. * @param target defines the target where the animation will take place
  25923. * @param animations defines the list of animations to start
  25924. * @param from defines the initial value
  25925. * @param to defines the final value
  25926. * @param loop defines if you want animation to loop (off by default)
  25927. * @param speedRatio defines the speed ratio to apply to all animations
  25928. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25929. * @returns the list of created animatables
  25930. */
  25931. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25932. if (speedRatio === undefined) {
  25933. speedRatio = 1.0;
  25934. }
  25935. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25936. return animatable;
  25937. };
  25938. /**
  25939. * Begin a new animation on a given node and its hierarchy
  25940. * @param target defines the root node where the animation will take place
  25941. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25942. * @param animations defines the list of animations to start
  25943. * @param from defines the initial value
  25944. * @param to defines the final value
  25945. * @param loop defines if you want animation to loop (off by default)
  25946. * @param speedRatio defines the speed ratio to apply to all animations
  25947. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25948. * @returns the list of animatables created for all nodes
  25949. */
  25950. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25951. var children = target.getDescendants(directDescendantsOnly);
  25952. var result = [];
  25953. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25954. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25955. var child = children_1[_i];
  25956. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25957. }
  25958. return result;
  25959. };
  25960. /**
  25961. * Gets the animatable associated with a specific target
  25962. * @param target defines the target of the animatable
  25963. * @returns the required animatable if found
  25964. */
  25965. Scene.prototype.getAnimatableByTarget = function (target) {
  25966. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25967. if (this._activeAnimatables[index].target === target) {
  25968. return this._activeAnimatables[index];
  25969. }
  25970. }
  25971. return null;
  25972. };
  25973. /**
  25974. * Gets all animatables associated with a given target
  25975. * @param target defines the target to look animatables for
  25976. * @returns an array of Animatables
  25977. */
  25978. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25979. var result = [];
  25980. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25981. if (this._activeAnimatables[index].target === target) {
  25982. result.push(this._activeAnimatables[index]);
  25983. }
  25984. }
  25985. return result;
  25986. };
  25987. Object.defineProperty(Scene.prototype, "animatables", {
  25988. /**
  25989. * Gets all animatable attached to the scene
  25990. */
  25991. get: function () {
  25992. return this._activeAnimatables;
  25993. },
  25994. enumerable: true,
  25995. configurable: true
  25996. });
  25997. /**
  25998. * Will stop the animation of the given target
  25999. * @param target - the target
  26000. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26001. */
  26002. Scene.prototype.stopAnimation = function (target, animationName) {
  26003. var animatables = this.getAllAnimatablesByTarget(target);
  26004. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26005. var animatable = animatables_1[_i];
  26006. animatable.stop(animationName);
  26007. }
  26008. };
  26009. /**
  26010. * Stops and removes all animations that have been applied to the scene
  26011. */
  26012. Scene.prototype.stopAllAnimations = function () {
  26013. if (this._activeAnimatables) {
  26014. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26015. this._activeAnimatables[i].stop();
  26016. }
  26017. this._activeAnimatables = [];
  26018. }
  26019. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26020. var group = _a[_i];
  26021. group.stop();
  26022. }
  26023. };
  26024. Scene.prototype._animate = function () {
  26025. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26026. return;
  26027. }
  26028. // Getting time
  26029. var now = BABYLON.Tools.Now;
  26030. if (!this._animationTimeLast) {
  26031. if (this._pendingData.length > 0) {
  26032. return;
  26033. }
  26034. this._animationTimeLast = now;
  26035. }
  26036. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26037. this._animationTime += deltaTime;
  26038. this._animationTimeLast = now;
  26039. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26040. this._activeAnimatables[index]._animate(this._animationTime);
  26041. }
  26042. // Late animation bindings
  26043. this._processLateAnimationBindings();
  26044. };
  26045. /** @hidden */
  26046. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26047. var target = runtimeAnimation.target;
  26048. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26049. if (!target._lateAnimationHolders) {
  26050. target._lateAnimationHolders = {};
  26051. }
  26052. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26053. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26054. totalWeight: 0,
  26055. animations: [],
  26056. originalValue: originalValue
  26057. };
  26058. }
  26059. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26060. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26061. };
  26062. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26063. var normalizer = 1.0;
  26064. var finalPosition = BABYLON.Tmp.Vector3[0];
  26065. var finalScaling = BABYLON.Tmp.Vector3[1];
  26066. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26067. var startIndex = 0;
  26068. var originalAnimation = holder.animations[0];
  26069. var originalValue = holder.originalValue;
  26070. var scale = 1;
  26071. if (holder.totalWeight < 1.0) {
  26072. // We need to mix the original value in
  26073. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26074. scale = 1.0 - holder.totalWeight;
  26075. }
  26076. else {
  26077. startIndex = 1;
  26078. // We need to normalize the weights
  26079. normalizer = holder.totalWeight;
  26080. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26081. scale = originalAnimation.weight / normalizer;
  26082. if (scale == 1) {
  26083. return originalAnimation.currentValue;
  26084. }
  26085. }
  26086. finalScaling.scaleInPlace(scale);
  26087. finalPosition.scaleInPlace(scale);
  26088. finalQuaternion.scaleInPlace(scale);
  26089. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26090. var runtimeAnimation = holder.animations[animIndex];
  26091. var scale = runtimeAnimation.weight / normalizer;
  26092. var currentPosition = BABYLON.Tmp.Vector3[2];
  26093. var currentScaling = BABYLON.Tmp.Vector3[3];
  26094. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26095. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26096. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26097. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26098. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26099. }
  26100. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26101. return originalAnimation._workValue;
  26102. };
  26103. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26104. var originalAnimation = holder.animations[0];
  26105. var originalValue = holder.originalValue;
  26106. if (holder.animations.length === 1) {
  26107. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26108. }
  26109. var normalizer = 1.0;
  26110. var quaternions;
  26111. var weights;
  26112. if (holder.totalWeight < 1.0) {
  26113. var scale = 1.0 - holder.totalWeight;
  26114. quaternions = [];
  26115. weights = [];
  26116. quaternions.push(originalValue);
  26117. weights.push(scale);
  26118. }
  26119. else {
  26120. if (holder.animations.length === 2) { // Slerp as soon as we can
  26121. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26122. }
  26123. quaternions = [];
  26124. weights = [];
  26125. normalizer = holder.totalWeight;
  26126. }
  26127. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26128. var runtimeAnimation = holder.animations[animIndex];
  26129. quaternions.push(runtimeAnimation.currentValue);
  26130. weights.push(runtimeAnimation.weight / normalizer);
  26131. }
  26132. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26133. var cumulativeAmount = 0;
  26134. var cumulativeQuaternion = null;
  26135. for (var index = 0; index < quaternions.length;) {
  26136. if (!cumulativeQuaternion) {
  26137. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26138. cumulativeAmount = weights[index] + weights[index + 1];
  26139. index += 2;
  26140. continue;
  26141. }
  26142. cumulativeAmount += weights[index];
  26143. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26144. index++;
  26145. }
  26146. return cumulativeQuaternion;
  26147. };
  26148. Scene.prototype._processLateAnimationBindings = function () {
  26149. if (!this._registeredForLateAnimationBindings.length) {
  26150. return;
  26151. }
  26152. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26153. var target = this._registeredForLateAnimationBindings.data[index];
  26154. for (var path in target._lateAnimationHolders) {
  26155. var holder = target._lateAnimationHolders[path];
  26156. var originalAnimation = holder.animations[0];
  26157. var originalValue = holder.originalValue;
  26158. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26159. var finalValue = void 0;
  26160. if (matrixDecomposeMode) {
  26161. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26162. }
  26163. else {
  26164. var quaternionMode = originalValue.w !== undefined;
  26165. if (quaternionMode) {
  26166. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26167. }
  26168. else {
  26169. var startIndex = 0;
  26170. var normalizer = 1.0;
  26171. if (holder.totalWeight < 1.0) {
  26172. // We need to mix the original value in
  26173. if (originalValue.scale) {
  26174. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26175. }
  26176. else {
  26177. finalValue = originalValue * (1.0 - holder.totalWeight);
  26178. }
  26179. }
  26180. else {
  26181. // We need to normalize the weights
  26182. normalizer = holder.totalWeight;
  26183. var scale_1 = originalAnimation.weight / normalizer;
  26184. if (scale_1 !== 1) {
  26185. if (originalAnimation.currentValue.scale) {
  26186. finalValue = originalAnimation.currentValue.scale(scale_1);
  26187. }
  26188. else {
  26189. finalValue = originalAnimation.currentValue * scale_1;
  26190. }
  26191. }
  26192. else {
  26193. finalValue = originalAnimation.currentValue;
  26194. }
  26195. startIndex = 1;
  26196. }
  26197. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26198. var runtimeAnimation = holder.animations[animIndex];
  26199. var scale = runtimeAnimation.weight / normalizer;
  26200. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26201. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26202. }
  26203. else {
  26204. finalValue += runtimeAnimation.currentValue * scale;
  26205. }
  26206. }
  26207. }
  26208. }
  26209. target[path] = finalValue;
  26210. }
  26211. target._lateAnimationHolders = {};
  26212. }
  26213. this._registeredForLateAnimationBindings.reset();
  26214. };
  26215. // Matrix
  26216. /** @hidden */
  26217. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26218. this._useAlternateCameraConfiguration = active;
  26219. };
  26220. /**
  26221. * Gets the current view matrix
  26222. * @returns a Matrix
  26223. */
  26224. Scene.prototype.getViewMatrix = function () {
  26225. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26226. };
  26227. /**
  26228. * Gets the current projection matrix
  26229. * @returns a Matrix
  26230. */
  26231. Scene.prototype.getProjectionMatrix = function () {
  26232. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26233. };
  26234. /**
  26235. * Gets the current transform matrix
  26236. * @returns a Matrix made of View * Projection
  26237. */
  26238. Scene.prototype.getTransformMatrix = function () {
  26239. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26240. };
  26241. /**
  26242. * Sets the current transform matrix
  26243. * @param view defines the View matrix to use
  26244. * @param projection defines the Projection matrix to use
  26245. */
  26246. Scene.prototype.setTransformMatrix = function (view, projection) {
  26247. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26248. return;
  26249. }
  26250. this._viewUpdateFlag = view.updateFlag;
  26251. this._projectionUpdateFlag = projection.updateFlag;
  26252. this._viewMatrix = view;
  26253. this._projectionMatrix = projection;
  26254. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26255. // Update frustum
  26256. if (!this._frustumPlanes) {
  26257. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26258. }
  26259. else {
  26260. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26261. }
  26262. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26263. var otherCamera = this.activeCamera._alternateCamera;
  26264. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26265. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26266. }
  26267. if (this._sceneUbo.useUbo) {
  26268. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26269. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26270. this._sceneUbo.update();
  26271. }
  26272. };
  26273. /** @hidden */
  26274. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26275. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26276. return;
  26277. }
  26278. this._alternateViewUpdateFlag = view.updateFlag;
  26279. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26280. this._alternateViewMatrix = view;
  26281. this._alternateProjectionMatrix = projection;
  26282. if (!this._alternateTransformMatrix) {
  26283. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26284. }
  26285. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26286. if (!this._alternateSceneUbo) {
  26287. this._createAlternateUbo();
  26288. }
  26289. if (this._alternateSceneUbo.useUbo) {
  26290. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26291. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26292. this._alternateSceneUbo.update();
  26293. }
  26294. };
  26295. /**
  26296. * Gets the uniform buffer used to store scene data
  26297. * @returns a UniformBuffer
  26298. */
  26299. Scene.prototype.getSceneUniformBuffer = function () {
  26300. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26301. };
  26302. /**
  26303. * Gets an unique (relatively to the current scene) Id
  26304. * @returns an unique number for the scene
  26305. */
  26306. Scene.prototype.getUniqueId = function () {
  26307. var result = Scene._uniqueIdCounter;
  26308. Scene._uniqueIdCounter++;
  26309. return result;
  26310. };
  26311. /**
  26312. * Add a mesh to the list of scene's meshes
  26313. * @param newMesh defines the mesh to add
  26314. * @param recursive if all child meshes should also be added to the scene
  26315. */
  26316. Scene.prototype.addMesh = function (newMesh, recursive) {
  26317. var _this = this;
  26318. if (recursive === void 0) { recursive = false; }
  26319. this.meshes.push(newMesh);
  26320. //notify the collision coordinator
  26321. if (this.collisionCoordinator) {
  26322. this.collisionCoordinator.onMeshAdded(newMesh);
  26323. }
  26324. newMesh._resyncLightSources();
  26325. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26326. if (recursive) {
  26327. newMesh.getChildMeshes().forEach(function (m) {
  26328. _this.addMesh(m);
  26329. });
  26330. }
  26331. };
  26332. /**
  26333. * Remove a mesh for the list of scene's meshes
  26334. * @param toRemove defines the mesh to remove
  26335. * @param recursive if all child meshes should also be removed from the scene
  26336. * @returns the index where the mesh was in the mesh list
  26337. */
  26338. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26339. var _this = this;
  26340. if (recursive === void 0) { recursive = false; }
  26341. var index = this.meshes.indexOf(toRemove);
  26342. if (index !== -1) {
  26343. // Remove from the scene if mesh found
  26344. this.meshes.splice(index, 1);
  26345. }
  26346. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26347. if (recursive) {
  26348. toRemove.getChildMeshes().forEach(function (m) {
  26349. _this.removeMesh(m);
  26350. });
  26351. }
  26352. return index;
  26353. };
  26354. /**
  26355. * Add a transform node to the list of scene's transform nodes
  26356. * @param newTransformNode defines the transform node to add
  26357. */
  26358. Scene.prototype.addTransformNode = function (newTransformNode) {
  26359. this.transformNodes.push(newTransformNode);
  26360. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26361. };
  26362. /**
  26363. * Remove a transform node for the list of scene's transform nodes
  26364. * @param toRemove defines the transform node to remove
  26365. * @returns the index where the transform node was in the transform node list
  26366. */
  26367. Scene.prototype.removeTransformNode = function (toRemove) {
  26368. var index = this.transformNodes.indexOf(toRemove);
  26369. if (index !== -1) {
  26370. // Remove from the scene if found
  26371. this.transformNodes.splice(index, 1);
  26372. }
  26373. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26374. return index;
  26375. };
  26376. /**
  26377. * Remove a skeleton for the list of scene's skeletons
  26378. * @param toRemove defines the skeleton to remove
  26379. * @returns the index where the skeleton was in the skeleton list
  26380. */
  26381. Scene.prototype.removeSkeleton = function (toRemove) {
  26382. var index = this.skeletons.indexOf(toRemove);
  26383. if (index !== -1) {
  26384. // Remove from the scene if found
  26385. this.skeletons.splice(index, 1);
  26386. }
  26387. return index;
  26388. };
  26389. /**
  26390. * Remove a morph target for the list of scene's morph targets
  26391. * @param toRemove defines the morph target to remove
  26392. * @returns the index where the morph target was in the morph target list
  26393. */
  26394. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26395. var index = this.morphTargetManagers.indexOf(toRemove);
  26396. if (index !== -1) {
  26397. // Remove from the scene if found
  26398. this.morphTargetManagers.splice(index, 1);
  26399. }
  26400. return index;
  26401. };
  26402. /**
  26403. * Remove a light for the list of scene's lights
  26404. * @param toRemove defines the light to remove
  26405. * @returns the index where the light was in the light list
  26406. */
  26407. Scene.prototype.removeLight = function (toRemove) {
  26408. var index = this.lights.indexOf(toRemove);
  26409. if (index !== -1) {
  26410. // Remove from meshes
  26411. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26412. var mesh = _a[_i];
  26413. mesh._removeLightSource(toRemove);
  26414. }
  26415. // Remove from the scene if mesh found
  26416. this.lights.splice(index, 1);
  26417. this.sortLightsByPriority();
  26418. }
  26419. this.onLightRemovedObservable.notifyObservers(toRemove);
  26420. return index;
  26421. };
  26422. /**
  26423. * Remove a camera for the list of scene's cameras
  26424. * @param toRemove defines the camera to remove
  26425. * @returns the index where the camera was in the camera list
  26426. */
  26427. Scene.prototype.removeCamera = function (toRemove) {
  26428. var index = this.cameras.indexOf(toRemove);
  26429. if (index !== -1) {
  26430. // Remove from the scene if mesh found
  26431. this.cameras.splice(index, 1);
  26432. }
  26433. // Remove from activeCameras
  26434. var index2 = this.activeCameras.indexOf(toRemove);
  26435. if (index2 !== -1) {
  26436. // Remove from the scene if mesh found
  26437. this.activeCameras.splice(index2, 1);
  26438. }
  26439. // Reset the activeCamera
  26440. if (this.activeCamera === toRemove) {
  26441. if (this.cameras.length > 0) {
  26442. this.activeCamera = this.cameras[0];
  26443. }
  26444. else {
  26445. this.activeCamera = null;
  26446. }
  26447. }
  26448. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26449. return index;
  26450. };
  26451. /**
  26452. * Remove a particle system for the list of scene's particle systems
  26453. * @param toRemove defines the particle system to remove
  26454. * @returns the index where the particle system was in the particle system list
  26455. */
  26456. Scene.prototype.removeParticleSystem = function (toRemove) {
  26457. var index = this.particleSystems.indexOf(toRemove);
  26458. if (index !== -1) {
  26459. this.particleSystems.splice(index, 1);
  26460. }
  26461. return index;
  26462. };
  26463. /**
  26464. * Remove a animation for the list of scene's animations
  26465. * @param toRemove defines the animation to remove
  26466. * @returns the index where the animation was in the animation list
  26467. */
  26468. Scene.prototype.removeAnimation = function (toRemove) {
  26469. var index = this.animations.indexOf(toRemove);
  26470. if (index !== -1) {
  26471. this.animations.splice(index, 1);
  26472. }
  26473. return index;
  26474. };
  26475. /**
  26476. * Removes the given animation group from this scene.
  26477. * @param toRemove The animation group to remove
  26478. * @returns The index of the removed animation group
  26479. */
  26480. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26481. var index = this.animationGroups.indexOf(toRemove);
  26482. if (index !== -1) {
  26483. this.animationGroups.splice(index, 1);
  26484. }
  26485. return index;
  26486. };
  26487. /**
  26488. * Removes the given multi-material from this scene.
  26489. * @param toRemove The multi-material to remove
  26490. * @returns The index of the removed multi-material
  26491. */
  26492. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26493. var index = this.multiMaterials.indexOf(toRemove);
  26494. if (index !== -1) {
  26495. this.multiMaterials.splice(index, 1);
  26496. }
  26497. return index;
  26498. };
  26499. /**
  26500. * Removes the given material from this scene.
  26501. * @param toRemove The material to remove
  26502. * @returns The index of the removed material
  26503. */
  26504. Scene.prototype.removeMaterial = function (toRemove) {
  26505. var index = this.materials.indexOf(toRemove);
  26506. if (index !== -1) {
  26507. this.materials.splice(index, 1);
  26508. }
  26509. return index;
  26510. };
  26511. /**
  26512. * Removes the given lens flare system from this scene.
  26513. * @param toRemove The lens flare system to remove
  26514. * @returns The index of the removed lens flare system
  26515. */
  26516. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26517. var index = this.lensFlareSystems.indexOf(toRemove);
  26518. if (index !== -1) {
  26519. this.lensFlareSystems.splice(index, 1);
  26520. }
  26521. return index;
  26522. };
  26523. /**
  26524. * Removes the given action manager from this scene.
  26525. * @param toRemove The action manager to remove
  26526. * @returns The index of the removed action manager
  26527. */
  26528. Scene.prototype.removeActionManager = function (toRemove) {
  26529. var index = this._actionManagers.indexOf(toRemove);
  26530. if (index !== -1) {
  26531. this._actionManagers.splice(index, 1);
  26532. }
  26533. return index;
  26534. };
  26535. /**
  26536. * Removes the given effect layer from this scene.
  26537. * @param toRemove defines the effect layer to remove
  26538. * @returns the index of the removed effect layer
  26539. */
  26540. Scene.prototype.removeEffectLayer = function (toRemove) {
  26541. var index = this.effectLayers.indexOf(toRemove);
  26542. if (index !== -1) {
  26543. this.effectLayers.splice(index, 1);
  26544. }
  26545. return index;
  26546. };
  26547. /**
  26548. * Removes the given texture from this scene.
  26549. * @param toRemove The texture to remove
  26550. * @returns The index of the removed texture
  26551. */
  26552. Scene.prototype.removeTexture = function (toRemove) {
  26553. var index = this.textures.indexOf(toRemove);
  26554. if (index !== -1) {
  26555. this.textures.splice(index, 1);
  26556. }
  26557. return index;
  26558. };
  26559. /**
  26560. * Adds the given light to this scene
  26561. * @param newLight The light to add
  26562. */
  26563. Scene.prototype.addLight = function (newLight) {
  26564. this.lights.push(newLight);
  26565. this.sortLightsByPriority();
  26566. // Add light to all meshes (To support if the light is removed and then readded)
  26567. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26568. var mesh = _a[_i];
  26569. if (mesh._lightSources.indexOf(newLight) === -1) {
  26570. mesh._lightSources.push(newLight);
  26571. mesh._resyncLightSources();
  26572. }
  26573. }
  26574. this.onNewLightAddedObservable.notifyObservers(newLight);
  26575. };
  26576. /**
  26577. * Sorts the list list based on light priorities
  26578. */
  26579. Scene.prototype.sortLightsByPriority = function () {
  26580. if (this.requireLightSorting) {
  26581. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26582. }
  26583. };
  26584. /**
  26585. * Adds the given camera to this scene
  26586. * @param newCamera The camera to add
  26587. */
  26588. Scene.prototype.addCamera = function (newCamera) {
  26589. this.cameras.push(newCamera);
  26590. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26591. };
  26592. /**
  26593. * Adds the given skeleton to this scene
  26594. * @param newSkeleton The skeleton to add
  26595. */
  26596. Scene.prototype.addSkeleton = function (newSkeleton) {
  26597. this.skeletons.push(newSkeleton);
  26598. };
  26599. /**
  26600. * Adds the given particle system to this scene
  26601. * @param newParticleSystem The particle system to add
  26602. */
  26603. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26604. this.particleSystems.push(newParticleSystem);
  26605. };
  26606. /**
  26607. * Adds the given animation to this scene
  26608. * @param newAnimation The animation to add
  26609. */
  26610. Scene.prototype.addAnimation = function (newAnimation) {
  26611. this.animations.push(newAnimation);
  26612. };
  26613. /**
  26614. * Adds the given animation group to this scene.
  26615. * @param newAnimationGroup The animation group to add
  26616. */
  26617. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26618. this.animationGroups.push(newAnimationGroup);
  26619. };
  26620. /**
  26621. * Adds the given multi-material to this scene
  26622. * @param newMultiMaterial The multi-material to add
  26623. */
  26624. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26625. this.multiMaterials.push(newMultiMaterial);
  26626. };
  26627. /**
  26628. * Adds the given material to this scene
  26629. * @param newMaterial The material to add
  26630. */
  26631. Scene.prototype.addMaterial = function (newMaterial) {
  26632. this.materials.push(newMaterial);
  26633. };
  26634. /**
  26635. * Adds the given morph target to this scene
  26636. * @param newMorphTargetManager The morph target to add
  26637. */
  26638. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26639. this.morphTargetManagers.push(newMorphTargetManager);
  26640. };
  26641. /**
  26642. * Adds the given geometry to this scene
  26643. * @param newGeometry The geometry to add
  26644. */
  26645. Scene.prototype.addGeometry = function (newGeometry) {
  26646. this._geometries.push(newGeometry);
  26647. };
  26648. /**
  26649. * Adds the given lens flare system to this scene
  26650. * @param newLensFlareSystem The lens flare system to add
  26651. */
  26652. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26653. this.lensFlareSystems.push(newLensFlareSystem);
  26654. };
  26655. /**
  26656. * Adds the given effect layer to this scene
  26657. * @param newEffectLayer defines the effect layer to add
  26658. */
  26659. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26660. this.effectLayers.push(newEffectLayer);
  26661. };
  26662. /**
  26663. * Adds the given action manager to this scene
  26664. * @param newActionManager The action manager to add
  26665. */
  26666. Scene.prototype.addActionManager = function (newActionManager) {
  26667. this._actionManagers.push(newActionManager);
  26668. };
  26669. /**
  26670. * Adds the given texture to this scene.
  26671. * @param newTexture The texture to add
  26672. */
  26673. Scene.prototype.addTexture = function (newTexture) {
  26674. this.textures.push(newTexture);
  26675. };
  26676. /**
  26677. * Switch active camera
  26678. * @param newCamera defines the new active camera
  26679. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26680. */
  26681. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26682. if (attachControl === void 0) { attachControl = true; }
  26683. var canvas = this._engine.getRenderingCanvas();
  26684. if (!canvas) {
  26685. return;
  26686. }
  26687. if (this.activeCamera) {
  26688. this.activeCamera.detachControl(canvas);
  26689. }
  26690. this.activeCamera = newCamera;
  26691. if (attachControl) {
  26692. newCamera.attachControl(canvas);
  26693. }
  26694. };
  26695. /**
  26696. * sets the active camera of the scene using its ID
  26697. * @param id defines the camera's ID
  26698. * @return the new active camera or null if none found.
  26699. */
  26700. Scene.prototype.setActiveCameraByID = function (id) {
  26701. var camera = this.getCameraByID(id);
  26702. if (camera) {
  26703. this.activeCamera = camera;
  26704. return camera;
  26705. }
  26706. return null;
  26707. };
  26708. /**
  26709. * sets the active camera of the scene using its name
  26710. * @param name defines the camera's name
  26711. * @returns the new active camera or null if none found.
  26712. */
  26713. Scene.prototype.setActiveCameraByName = function (name) {
  26714. var camera = this.getCameraByName(name);
  26715. if (camera) {
  26716. this.activeCamera = camera;
  26717. return camera;
  26718. }
  26719. return null;
  26720. };
  26721. /**
  26722. * get an animation group using its name
  26723. * @param name defines the material's name
  26724. * @return the animation group or null if none found.
  26725. */
  26726. Scene.prototype.getAnimationGroupByName = function (name) {
  26727. for (var index = 0; index < this.animationGroups.length; index++) {
  26728. if (this.animationGroups[index].name === name) {
  26729. return this.animationGroups[index];
  26730. }
  26731. }
  26732. return null;
  26733. };
  26734. /**
  26735. * get a material using its id
  26736. * @param id defines the material's ID
  26737. * @return the material or null if none found.
  26738. */
  26739. Scene.prototype.getMaterialByID = function (id) {
  26740. for (var index = 0; index < this.materials.length; index++) {
  26741. if (this.materials[index].id === id) {
  26742. return this.materials[index];
  26743. }
  26744. }
  26745. return null;
  26746. };
  26747. /**
  26748. * Gets a material using its name
  26749. * @param name defines the material's name
  26750. * @return the material or null if none found.
  26751. */
  26752. Scene.prototype.getMaterialByName = function (name) {
  26753. for (var index = 0; index < this.materials.length; index++) {
  26754. if (this.materials[index].name === name) {
  26755. return this.materials[index];
  26756. }
  26757. }
  26758. return null;
  26759. };
  26760. /**
  26761. * Gets a lens flare system using its name
  26762. * @param name defines the name to look for
  26763. * @returns the lens flare system or null if not found
  26764. */
  26765. Scene.prototype.getLensFlareSystemByName = function (name) {
  26766. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26767. if (this.lensFlareSystems[index].name === name) {
  26768. return this.lensFlareSystems[index];
  26769. }
  26770. }
  26771. return null;
  26772. };
  26773. /**
  26774. * Gets a lens flare system using its id
  26775. * @param id defines the id to look for
  26776. * @returns the lens flare system or null if not found
  26777. */
  26778. Scene.prototype.getLensFlareSystemByID = function (id) {
  26779. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26780. if (this.lensFlareSystems[index].id === id) {
  26781. return this.lensFlareSystems[index];
  26782. }
  26783. }
  26784. return null;
  26785. };
  26786. /**
  26787. * Gets a camera using its id
  26788. * @param id defines the id to look for
  26789. * @returns the camera or null if not found
  26790. */
  26791. Scene.prototype.getCameraByID = function (id) {
  26792. for (var index = 0; index < this.cameras.length; index++) {
  26793. if (this.cameras[index].id === id) {
  26794. return this.cameras[index];
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a camera using its unique id
  26801. * @param uniqueId defines the unique id to look for
  26802. * @returns the camera or null if not found
  26803. */
  26804. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26805. for (var index = 0; index < this.cameras.length; index++) {
  26806. if (this.cameras[index].uniqueId === uniqueId) {
  26807. return this.cameras[index];
  26808. }
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * Gets a camera using its name
  26814. * @param name defines the camera's name
  26815. * @return the camera or null if none found.
  26816. */
  26817. Scene.prototype.getCameraByName = function (name) {
  26818. for (var index = 0; index < this.cameras.length; index++) {
  26819. if (this.cameras[index].name === name) {
  26820. return this.cameras[index];
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * Gets a bone using its id
  26827. * @param id defines the bone's id
  26828. * @return the bone or null if not found
  26829. */
  26830. Scene.prototype.getBoneByID = function (id) {
  26831. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26832. var skeleton = this.skeletons[skeletonIndex];
  26833. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26834. if (skeleton.bones[boneIndex].id === id) {
  26835. return skeleton.bones[boneIndex];
  26836. }
  26837. }
  26838. }
  26839. return null;
  26840. };
  26841. /**
  26842. * Gets a bone using its id
  26843. * @param name defines the bone's name
  26844. * @return the bone or null if not found
  26845. */
  26846. Scene.prototype.getBoneByName = function (name) {
  26847. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26848. var skeleton = this.skeletons[skeletonIndex];
  26849. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26850. if (skeleton.bones[boneIndex].name === name) {
  26851. return skeleton.bones[boneIndex];
  26852. }
  26853. }
  26854. }
  26855. return null;
  26856. };
  26857. /**
  26858. * Gets a light node using its name
  26859. * @param name defines the the light's name
  26860. * @return the light or null if none found.
  26861. */
  26862. Scene.prototype.getLightByName = function (name) {
  26863. for (var index = 0; index < this.lights.length; index++) {
  26864. if (this.lights[index].name === name) {
  26865. return this.lights[index];
  26866. }
  26867. }
  26868. return null;
  26869. };
  26870. /**
  26871. * Gets a light node using its id
  26872. * @param id defines the light's id
  26873. * @return the light or null if none found.
  26874. */
  26875. Scene.prototype.getLightByID = function (id) {
  26876. for (var index = 0; index < this.lights.length; index++) {
  26877. if (this.lights[index].id === id) {
  26878. return this.lights[index];
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a light node using its scene-generated unique ID
  26885. * @param uniqueId defines the light's unique id
  26886. * @return the light or null if none found.
  26887. */
  26888. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26889. for (var index = 0; index < this.lights.length; index++) {
  26890. if (this.lights[index].uniqueId === uniqueId) {
  26891. return this.lights[index];
  26892. }
  26893. }
  26894. return null;
  26895. };
  26896. /**
  26897. * Gets a particle system by id
  26898. * @param id defines the particle system id
  26899. * @return the corresponding system or null if none found
  26900. */
  26901. Scene.prototype.getParticleSystemByID = function (id) {
  26902. for (var index = 0; index < this.particleSystems.length; index++) {
  26903. if (this.particleSystems[index].id === id) {
  26904. return this.particleSystems[index];
  26905. }
  26906. }
  26907. return null;
  26908. };
  26909. /**
  26910. * Gets a geometry using its ID
  26911. * @param id defines the geometry's id
  26912. * @return the geometry or null if none found.
  26913. */
  26914. Scene.prototype.getGeometryByID = function (id) {
  26915. for (var index = 0; index < this._geometries.length; index++) {
  26916. if (this._geometries[index].id === id) {
  26917. return this._geometries[index];
  26918. }
  26919. }
  26920. return null;
  26921. };
  26922. /**
  26923. * Add a new geometry to this scene
  26924. * @param geometry defines the geometry to be added to the scene.
  26925. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26926. * @return a boolean defining if the geometry was added or not
  26927. */
  26928. Scene.prototype.pushGeometry = function (geometry, force) {
  26929. if (!force && this.getGeometryByID(geometry.id)) {
  26930. return false;
  26931. }
  26932. this._geometries.push(geometry);
  26933. //notify the collision coordinator
  26934. if (this.collisionCoordinator) {
  26935. this.collisionCoordinator.onGeometryAdded(geometry);
  26936. }
  26937. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26938. return true;
  26939. };
  26940. /**
  26941. * Removes an existing geometry
  26942. * @param geometry defines the geometry to be removed from the scene
  26943. * @return a boolean defining if the geometry was removed or not
  26944. */
  26945. Scene.prototype.removeGeometry = function (geometry) {
  26946. var index = this._geometries.indexOf(geometry);
  26947. if (index > -1) {
  26948. this._geometries.splice(index, 1);
  26949. //notify the collision coordinator
  26950. if (this.collisionCoordinator) {
  26951. this.collisionCoordinator.onGeometryDeleted(geometry);
  26952. }
  26953. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26954. return true;
  26955. }
  26956. return false;
  26957. };
  26958. /**
  26959. * Gets the list of geometries attached to the scene
  26960. * @returns an array of Geometry
  26961. */
  26962. Scene.prototype.getGeometries = function () {
  26963. return this._geometries;
  26964. };
  26965. /**
  26966. * Gets the first added mesh found of a given ID
  26967. * @param id defines the id to search for
  26968. * @return the mesh found or null if not found at all
  26969. */
  26970. Scene.prototype.getMeshByID = function (id) {
  26971. for (var index = 0; index < this.meshes.length; index++) {
  26972. if (this.meshes[index].id === id) {
  26973. return this.meshes[index];
  26974. }
  26975. }
  26976. return null;
  26977. };
  26978. /**
  26979. * Gets a list of meshes using their id
  26980. * @param id defines the id to search for
  26981. * @returns a list of meshes
  26982. */
  26983. Scene.prototype.getMeshesByID = function (id) {
  26984. return this.meshes.filter(function (m) {
  26985. return m.id === id;
  26986. });
  26987. };
  26988. /**
  26989. * Gets the first added transform node found of a given ID
  26990. * @param id defines the id to search for
  26991. * @return the found transform node or null if not found at all.
  26992. */
  26993. Scene.prototype.getTransformNodeByID = function (id) {
  26994. for (var index = 0; index < this.transformNodes.length; index++) {
  26995. if (this.transformNodes[index].id === id) {
  26996. return this.transformNodes[index];
  26997. }
  26998. }
  26999. return null;
  27000. };
  27001. /**
  27002. * Gets a list of transform nodes using their id
  27003. * @param id defines the id to search for
  27004. * @returns a list of transform nodes
  27005. */
  27006. Scene.prototype.getTransformNodesByID = function (id) {
  27007. return this.transformNodes.filter(function (m) {
  27008. return m.id === id;
  27009. });
  27010. };
  27011. /**
  27012. * Gets a mesh with its auto-generated unique id
  27013. * @param uniqueId defines the unique id to search for
  27014. * @return the found mesh or null if not found at all.
  27015. */
  27016. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27017. for (var index = 0; index < this.meshes.length; index++) {
  27018. if (this.meshes[index].uniqueId === uniqueId) {
  27019. return this.meshes[index];
  27020. }
  27021. }
  27022. return null;
  27023. };
  27024. /**
  27025. * Gets a the last added mesh using a given id
  27026. * @param id defines the id to search for
  27027. * @return the found mesh or null if not found at all.
  27028. */
  27029. Scene.prototype.getLastMeshByID = function (id) {
  27030. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27031. if (this.meshes[index].id === id) {
  27032. return this.meshes[index];
  27033. }
  27034. }
  27035. return null;
  27036. };
  27037. /**
  27038. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27039. * @param id defines the id to search for
  27040. * @return the found node or null if not found at all
  27041. */
  27042. Scene.prototype.getLastEntryByID = function (id) {
  27043. var index;
  27044. for (index = this.meshes.length - 1; index >= 0; index--) {
  27045. if (this.meshes[index].id === id) {
  27046. return this.meshes[index];
  27047. }
  27048. }
  27049. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27050. if (this.transformNodes[index].id === id) {
  27051. return this.transformNodes[index];
  27052. }
  27053. }
  27054. for (index = this.cameras.length - 1; index >= 0; index--) {
  27055. if (this.cameras[index].id === id) {
  27056. return this.cameras[index];
  27057. }
  27058. }
  27059. for (index = this.lights.length - 1; index >= 0; index--) {
  27060. if (this.lights[index].id === id) {
  27061. return this.lights[index];
  27062. }
  27063. }
  27064. return null;
  27065. };
  27066. /**
  27067. * Gets a node (Mesh, Camera, Light) using a given id
  27068. * @param id defines the id to search for
  27069. * @return the found node or null if not found at all
  27070. */
  27071. Scene.prototype.getNodeByID = function (id) {
  27072. var mesh = this.getMeshByID(id);
  27073. if (mesh) {
  27074. return mesh;
  27075. }
  27076. var light = this.getLightByID(id);
  27077. if (light) {
  27078. return light;
  27079. }
  27080. var camera = this.getCameraByID(id);
  27081. if (camera) {
  27082. return camera;
  27083. }
  27084. var bone = this.getBoneByID(id);
  27085. return bone;
  27086. };
  27087. /**
  27088. * Gets a node (Mesh, Camera, Light) using a given name
  27089. * @param name defines the name to search for
  27090. * @return the found node or null if not found at all.
  27091. */
  27092. Scene.prototype.getNodeByName = function (name) {
  27093. var mesh = this.getMeshByName(name);
  27094. if (mesh) {
  27095. return mesh;
  27096. }
  27097. var light = this.getLightByName(name);
  27098. if (light) {
  27099. return light;
  27100. }
  27101. var camera = this.getCameraByName(name);
  27102. if (camera) {
  27103. return camera;
  27104. }
  27105. var bone = this.getBoneByName(name);
  27106. return bone;
  27107. };
  27108. /**
  27109. * Gets a mesh using a given name
  27110. * @param name defines the name to search for
  27111. * @return the found mesh or null if not found at all.
  27112. */
  27113. Scene.prototype.getMeshByName = function (name) {
  27114. for (var index = 0; index < this.meshes.length; index++) {
  27115. if (this.meshes[index].name === name) {
  27116. return this.meshes[index];
  27117. }
  27118. }
  27119. return null;
  27120. };
  27121. /**
  27122. * Gets a transform node using a given name
  27123. * @param name defines the name to search for
  27124. * @return the found transform node or null if not found at all.
  27125. */
  27126. Scene.prototype.getTransformNodeByName = function (name) {
  27127. for (var index = 0; index < this.transformNodes.length; index++) {
  27128. if (this.transformNodes[index].name === name) {
  27129. return this.transformNodes[index];
  27130. }
  27131. }
  27132. return null;
  27133. };
  27134. /**
  27135. * Gets a sound using a given name
  27136. * @param name defines the name to search for
  27137. * @return the found sound or null if not found at all.
  27138. */
  27139. Scene.prototype.getSoundByName = function (name) {
  27140. var index;
  27141. if (BABYLON.AudioEngine) {
  27142. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27143. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27144. return this.mainSoundTrack.soundCollection[index];
  27145. }
  27146. }
  27147. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27148. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27149. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27150. return this.soundTracks[sdIndex].soundCollection[index];
  27151. }
  27152. }
  27153. }
  27154. }
  27155. return null;
  27156. };
  27157. /**
  27158. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27159. * @param id defines the id to search for
  27160. * @return the found skeleton or null if not found at all.
  27161. */
  27162. Scene.prototype.getLastSkeletonByID = function (id) {
  27163. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27164. if (this.skeletons[index].id === id) {
  27165. return this.skeletons[index];
  27166. }
  27167. }
  27168. return null;
  27169. };
  27170. /**
  27171. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27172. * @param id defines the id to search for
  27173. * @return the found skeleton or null if not found at all.
  27174. */
  27175. Scene.prototype.getSkeletonById = function (id) {
  27176. for (var index = 0; index < this.skeletons.length; index++) {
  27177. if (this.skeletons[index].id === id) {
  27178. return this.skeletons[index];
  27179. }
  27180. }
  27181. return null;
  27182. };
  27183. /**
  27184. * Gets a skeleton using a given name
  27185. * @param name defines the name to search for
  27186. * @return the found skeleton or null if not found at all.
  27187. */
  27188. Scene.prototype.getSkeletonByName = function (name) {
  27189. for (var index = 0; index < this.skeletons.length; index++) {
  27190. if (this.skeletons[index].name === name) {
  27191. return this.skeletons[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27198. * @param id defines the id to search for
  27199. * @return the found morph target manager or null if not found at all.
  27200. */
  27201. Scene.prototype.getMorphTargetManagerById = function (id) {
  27202. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27203. if (this.morphTargetManagers[index].uniqueId === id) {
  27204. return this.morphTargetManagers[index];
  27205. }
  27206. }
  27207. return null;
  27208. };
  27209. /**
  27210. * Gets a boolean indicating if the given mesh is active
  27211. * @param mesh defines the mesh to look for
  27212. * @returns true if the mesh is in the active list
  27213. */
  27214. Scene.prototype.isActiveMesh = function (mesh) {
  27215. return (this._activeMeshes.indexOf(mesh) !== -1);
  27216. };
  27217. /**
  27218. * Return a the first highlight layer of the scene with a given name.
  27219. * @param name The name of the highlight layer to look for.
  27220. * @return The highlight layer if found otherwise null.
  27221. */
  27222. Scene.prototype.getHighlightLayerByName = function (name) {
  27223. for (var index = 0; index < this.effectLayers.length; index++) {
  27224. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27225. return this.effectLayers[index];
  27226. }
  27227. }
  27228. return null;
  27229. };
  27230. /**
  27231. * Return a the first highlight layer of the scene with a given name.
  27232. * @param name The name of the highlight layer to look for.
  27233. * @return The highlight layer if found otherwise null.
  27234. */
  27235. Scene.prototype.getGlowLayerByName = function (name) {
  27236. for (var index = 0; index < this.effectLayers.length; index++) {
  27237. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27238. return this.effectLayers[index];
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. Object.defineProperty(Scene.prototype, "uid", {
  27244. /**
  27245. * Return a unique id as a string which can serve as an identifier for the scene
  27246. */
  27247. get: function () {
  27248. if (!this._uid) {
  27249. this._uid = BABYLON.Tools.RandomId();
  27250. }
  27251. return this._uid;
  27252. },
  27253. enumerable: true,
  27254. configurable: true
  27255. });
  27256. /**
  27257. * Add an externaly attached data from its key.
  27258. * This method call will fail and return false, if such key already exists.
  27259. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27260. * @param key the unique key that identifies the data
  27261. * @param data the data object to associate to the key for this Engine instance
  27262. * @return true if no such key were already present and the data was added successfully, false otherwise
  27263. */
  27264. Scene.prototype.addExternalData = function (key, data) {
  27265. if (!this._externalData) {
  27266. this._externalData = new BABYLON.StringDictionary();
  27267. }
  27268. return this._externalData.add(key, data);
  27269. };
  27270. /**
  27271. * Get an externaly attached data from its key
  27272. * @param key the unique key that identifies the data
  27273. * @return the associated data, if present (can be null), or undefined if not present
  27274. */
  27275. Scene.prototype.getExternalData = function (key) {
  27276. if (!this._externalData) {
  27277. return null;
  27278. }
  27279. return this._externalData.get(key);
  27280. };
  27281. /**
  27282. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27283. * @param key the unique key that identifies the data
  27284. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27285. * @return the associated data, can be null if the factory returned null.
  27286. */
  27287. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27288. if (!this._externalData) {
  27289. this._externalData = new BABYLON.StringDictionary();
  27290. }
  27291. return this._externalData.getOrAddWithFactory(key, factory);
  27292. };
  27293. /**
  27294. * Remove an externaly attached data from the Engine instance
  27295. * @param key the unique key that identifies the data
  27296. * @return true if the data was successfully removed, false if it doesn't exist
  27297. */
  27298. Scene.prototype.removeExternalData = function (key) {
  27299. return this._externalData.remove(key);
  27300. };
  27301. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27302. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27303. if (mesh.showSubMeshesBoundingBox) {
  27304. var boundingInfo = subMesh.getBoundingInfo();
  27305. if (boundingInfo !== null && boundingInfo !== undefined) {
  27306. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27307. }
  27308. }
  27309. var material = subMesh.getMaterial();
  27310. if (material !== null && material !== undefined) {
  27311. // Render targets
  27312. if (material.getRenderTargetTextures !== undefined) {
  27313. if (this._processedMaterials.indexOf(material) === -1) {
  27314. this._processedMaterials.push(material);
  27315. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27316. }
  27317. }
  27318. // Dispatch
  27319. this._activeIndices.addCount(subMesh.indexCount, false);
  27320. this._renderingManager.dispatch(subMesh, mesh, material);
  27321. }
  27322. }
  27323. };
  27324. /**
  27325. * Clear the processed materials smart array preventing retention point in material dispose.
  27326. */
  27327. Scene.prototype.freeProcessedMaterials = function () {
  27328. this._processedMaterials.dispose();
  27329. };
  27330. /**
  27331. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27332. */
  27333. Scene.prototype.freeActiveMeshes = function () {
  27334. this._activeMeshes.dispose();
  27335. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27336. this.activeCamera._activeMeshes.dispose();
  27337. }
  27338. if (this.activeCameras) {
  27339. for (var i = 0; i < this.activeCameras.length; i++) {
  27340. var activeCamera = this.activeCameras[i];
  27341. if (activeCamera && activeCamera._activeMeshes) {
  27342. activeCamera._activeMeshes.dispose();
  27343. }
  27344. }
  27345. }
  27346. };
  27347. /**
  27348. * Clear the info related to rendering groups preventing retention points during dispose.
  27349. */
  27350. Scene.prototype.freeRenderingGroups = function () {
  27351. if (this._renderingManager) {
  27352. this._renderingManager.freeRenderingGroups();
  27353. }
  27354. if (this.textures) {
  27355. for (var i = 0; i < this.textures.length; i++) {
  27356. var texture = this.textures[i];
  27357. if (texture && texture.renderList) {
  27358. texture.freeRenderingGroups();
  27359. }
  27360. }
  27361. }
  27362. };
  27363. /** @hidden */
  27364. Scene.prototype._isInIntermediateRendering = function () {
  27365. return this._intermediateRendering;
  27366. };
  27367. /**
  27368. * Defines the current active mesh candidate provider
  27369. * @param provider defines the provider to use
  27370. */
  27371. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27372. this._activeMeshCandidateProvider = provider;
  27373. };
  27374. /**
  27375. * Gets the current active mesh candidate provider
  27376. * @returns the current active mesh candidate provider
  27377. */
  27378. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27379. return this._activeMeshCandidateProvider;
  27380. };
  27381. /**
  27382. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27383. * @returns the current scene
  27384. */
  27385. Scene.prototype.freezeActiveMeshes = function () {
  27386. if (!this.activeCamera) {
  27387. return this;
  27388. }
  27389. if (!this._frustumPlanes) {
  27390. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27391. }
  27392. this._evaluateActiveMeshes();
  27393. this._activeMeshesFrozen = true;
  27394. return this;
  27395. };
  27396. /**
  27397. * Use this function to restart evaluating active meshes on every frame
  27398. * @returns the current scene
  27399. */
  27400. Scene.prototype.unfreezeActiveMeshes = function () {
  27401. this._activeMeshesFrozen = false;
  27402. return this;
  27403. };
  27404. Scene.prototype._evaluateActiveMeshes = function () {
  27405. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27406. return;
  27407. }
  27408. if (!this.activeCamera) {
  27409. return;
  27410. }
  27411. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27412. this.activeCamera._activeMeshes.reset();
  27413. this._activeMeshes.reset();
  27414. this._renderingManager.reset();
  27415. this._processedMaterials.reset();
  27416. this._activeParticleSystems.reset();
  27417. this._activeSkeletons.reset();
  27418. this._softwareSkinnedMeshes.reset();
  27419. if (this._boundingBoxRenderer) {
  27420. this._boundingBoxRenderer.reset();
  27421. }
  27422. // Meshes
  27423. var meshes;
  27424. var len;
  27425. var checkIsEnabled = true;
  27426. // Determine mesh candidates
  27427. if (this._activeMeshCandidateProvider !== undefined) {
  27428. // Use _activeMeshCandidateProvider
  27429. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27430. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27431. if (meshes !== undefined) {
  27432. len = meshes.length;
  27433. }
  27434. else {
  27435. len = 0;
  27436. }
  27437. }
  27438. else if (this._selectionOctree !== undefined) {
  27439. // Octree
  27440. var selection = this._selectionOctree.select(this._frustumPlanes);
  27441. meshes = selection.data;
  27442. len = selection.length;
  27443. }
  27444. else {
  27445. // Full scene traversal
  27446. len = this.meshes.length;
  27447. meshes = this.meshes;
  27448. }
  27449. // Check each mesh
  27450. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27451. mesh = meshes[meshIndex];
  27452. if (mesh.isBlocked) {
  27453. continue;
  27454. }
  27455. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27456. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27457. continue;
  27458. }
  27459. mesh.computeWorldMatrix();
  27460. // Intersections
  27461. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27462. this._meshesForIntersections.pushNoDuplicate(mesh);
  27463. }
  27464. // Switch to current LOD
  27465. meshLOD = mesh.getLOD(this.activeCamera);
  27466. if (meshLOD === undefined || meshLOD === null) {
  27467. continue;
  27468. }
  27469. mesh._preActivate();
  27470. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27471. this._activeMeshes.push(mesh);
  27472. this.activeCamera._activeMeshes.push(mesh);
  27473. mesh._activate(this._renderId);
  27474. if (meshLOD !== mesh) {
  27475. meshLOD._activate(this._renderId);
  27476. }
  27477. this._activeMesh(mesh, meshLOD);
  27478. }
  27479. }
  27480. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27481. // Particle systems
  27482. if (this.particlesEnabled) {
  27483. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27484. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27485. var particleSystem = this.particleSystems[particleIndex];
  27486. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27487. continue;
  27488. }
  27489. var emitter = particleSystem.emitter;
  27490. if (!emitter.position || emitter.isEnabled()) {
  27491. this._activeParticleSystems.push(particleSystem);
  27492. particleSystem.animate();
  27493. this._renderingManager.dispatchParticles(particleSystem);
  27494. }
  27495. }
  27496. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27497. }
  27498. };
  27499. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27500. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27501. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27502. mesh.skeleton.prepare();
  27503. }
  27504. if (!mesh.computeBonesUsingShaders) {
  27505. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27506. }
  27507. }
  27508. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27509. var boundingInfo = sourceMesh.getBoundingInfo();
  27510. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27511. }
  27512. if (mesh !== undefined && mesh !== null
  27513. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27514. // Submeshes Octrees
  27515. var len;
  27516. var subMeshes;
  27517. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27518. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27519. len = intersections.length;
  27520. subMeshes = intersections.data;
  27521. }
  27522. else {
  27523. subMeshes = mesh.subMeshes;
  27524. len = subMeshes.length;
  27525. }
  27526. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27527. subMesh = subMeshes[subIndex];
  27528. this._evaluateSubMesh(subMesh, mesh);
  27529. }
  27530. }
  27531. };
  27532. /**
  27533. * Update the transform matrix to update from the current active camera
  27534. * @param force defines a boolean used to force the update even if cache is up to date
  27535. */
  27536. Scene.prototype.updateTransformMatrix = function (force) {
  27537. if (!this.activeCamera) {
  27538. return;
  27539. }
  27540. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27541. };
  27542. /**
  27543. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27544. * @param alternateCamera defines the camera to use
  27545. */
  27546. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27547. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27548. };
  27549. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27550. if (camera && camera._skipRendering) {
  27551. return;
  27552. }
  27553. var engine = this._engine;
  27554. this.activeCamera = camera;
  27555. if (!this.activeCamera)
  27556. throw new Error("Active camera not set");
  27557. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27558. // Viewport
  27559. engine.setViewport(this.activeCamera.viewport);
  27560. // Camera
  27561. this.resetCachedMaterial();
  27562. this._renderId++;
  27563. this.updateTransformMatrix();
  27564. if (camera._alternateCamera) {
  27565. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27566. this._alternateRendering = true;
  27567. }
  27568. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27569. // Meshes
  27570. this._evaluateActiveMeshes();
  27571. // Software skinning
  27572. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27573. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27574. mesh.applySkeleton(mesh.skeleton);
  27575. }
  27576. // Render targets
  27577. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27578. var needsRestoreFrameBuffer = false;
  27579. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27580. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27581. }
  27582. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27583. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27584. }
  27585. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27586. this._intermediateRendering = true;
  27587. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27588. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27589. var renderTarget = this._renderTargets.data[renderIndex];
  27590. if (renderTarget._shouldRender()) {
  27591. this._renderId++;
  27592. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27593. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27594. }
  27595. }
  27596. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27597. this._intermediateRendering = false;
  27598. this._renderId++;
  27599. needsRestoreFrameBuffer = true; // Restore back buffer
  27600. }
  27601. // Render EffecttLayer Texture
  27602. var stencilState = this._engine.getStencilBuffer();
  27603. var renderEffects = false;
  27604. var needStencil = false;
  27605. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27606. this._intermediateRendering = true;
  27607. for (var i = 0; i < this.effectLayers.length; i++) {
  27608. var effectLayer = this.effectLayers[i];
  27609. if (effectLayer.shouldRender() &&
  27610. (!effectLayer.camera ||
  27611. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27612. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27613. renderEffects = true;
  27614. needStencil = needStencil || effectLayer.needStencil();
  27615. var renderTarget = effectLayer._mainTexture;
  27616. if (renderTarget._shouldRender()) {
  27617. this._renderId++;
  27618. renderTarget.render(false, false);
  27619. needsRestoreFrameBuffer = true;
  27620. }
  27621. }
  27622. }
  27623. this._intermediateRendering = false;
  27624. this._renderId++;
  27625. }
  27626. if (needsRestoreFrameBuffer) {
  27627. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27628. }
  27629. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27630. // Prepare Frame
  27631. this.postProcessManager._prepareFrame();
  27632. // Backgrounds
  27633. var layerIndex;
  27634. var layer;
  27635. if (this.layers.length) {
  27636. engine.setDepthBuffer(false);
  27637. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27638. layer = this.layers[layerIndex];
  27639. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27640. layer.render();
  27641. }
  27642. }
  27643. engine.setDepthBuffer(true);
  27644. }
  27645. // Activate effect Layer stencil
  27646. if (needStencil) {
  27647. this._engine.setStencilBuffer(true);
  27648. }
  27649. // Render
  27650. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27651. this._renderingManager.render(null, null, true, true);
  27652. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27653. // Restore effect Layer stencil
  27654. if (needStencil) {
  27655. this._engine.setStencilBuffer(stencilState);
  27656. }
  27657. // Bounding boxes
  27658. if (this._boundingBoxRenderer) {
  27659. this._boundingBoxRenderer.render();
  27660. }
  27661. // Lens flares
  27662. if (this.lensFlaresEnabled) {
  27663. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27664. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27665. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27666. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27667. lensFlareSystem.render();
  27668. }
  27669. }
  27670. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27671. }
  27672. // Effect Layer
  27673. if (renderEffects) {
  27674. engine.setDepthBuffer(false);
  27675. for (var i = 0; i < this.effectLayers.length; i++) {
  27676. if (this.effectLayers[i].shouldRender()) {
  27677. this.effectLayers[i].render();
  27678. }
  27679. }
  27680. engine.setDepthBuffer(true);
  27681. }
  27682. // Foregrounds
  27683. if (this.layers.length) {
  27684. engine.setDepthBuffer(false);
  27685. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27686. layer = this.layers[layerIndex];
  27687. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27688. layer.render();
  27689. }
  27690. }
  27691. engine.setDepthBuffer(true);
  27692. }
  27693. // Finalize frame
  27694. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27695. // Reset some special arrays
  27696. this._renderTargets.reset();
  27697. this._alternateRendering = false;
  27698. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27699. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27700. };
  27701. Scene.prototype._processSubCameras = function (camera) {
  27702. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27703. this._renderForCamera(camera);
  27704. return;
  27705. }
  27706. // rig cameras
  27707. for (var index = 0; index < camera._rigCameras.length; index++) {
  27708. this._renderForCamera(camera._rigCameras[index], camera);
  27709. }
  27710. this.activeCamera = camera;
  27711. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27712. };
  27713. Scene.prototype._checkIntersections = function () {
  27714. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27715. var sourceMesh = this._meshesForIntersections.data[index];
  27716. if (!sourceMesh.actionManager) {
  27717. continue;
  27718. }
  27719. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27720. var action = sourceMesh.actionManager.actions[actionIndex];
  27721. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27722. var parameters = action.getTriggerParameter();
  27723. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27724. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27725. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27726. if (areIntersecting && currentIntersectionInProgress === -1) {
  27727. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27728. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27729. sourceMesh._intersectionsInProgress.push(otherMesh);
  27730. }
  27731. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27732. sourceMesh._intersectionsInProgress.push(otherMesh);
  27733. }
  27734. }
  27735. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27736. //They intersected, and now they don't.
  27737. //is this trigger an exit trigger? execute an event.
  27738. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27739. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27740. }
  27741. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27742. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27743. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27744. return otherMesh === parameterMesh;
  27745. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27746. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27747. }
  27748. }
  27749. }
  27750. }
  27751. }
  27752. };
  27753. /**
  27754. * Render the scene
  27755. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27756. */
  27757. Scene.prototype.render = function (updateCameras) {
  27758. if (updateCameras === void 0) { updateCameras = true; }
  27759. if (this.isDisposed) {
  27760. return;
  27761. }
  27762. this._activeParticles.fetchNewFrame();
  27763. this._totalVertices.fetchNewFrame();
  27764. this._activeIndices.fetchNewFrame();
  27765. this._activeBones.fetchNewFrame();
  27766. this._meshesForIntersections.reset();
  27767. this.resetCachedMaterial();
  27768. this.onBeforeAnimationsObservable.notifyObservers(this);
  27769. // Actions
  27770. if (this.actionManager) {
  27771. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27772. }
  27773. //Simplification Queue
  27774. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27775. this.simplificationQueue.executeNext();
  27776. }
  27777. if (this._engine.isDeterministicLockStep()) {
  27778. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27779. var defaultFPS = (60.0 / 1000.0);
  27780. var defaultFrameTime = 1000 / 60; // frame time in MS
  27781. if (this._physicsEngine) {
  27782. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27783. }
  27784. var stepsTaken = 0;
  27785. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27786. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27787. internalSteps = Math.min(internalSteps, maxSubSteps);
  27788. do {
  27789. this.onBeforeStepObservable.notifyObservers(this);
  27790. // Animations
  27791. this._animationRatio = defaultFrameTime * defaultFPS;
  27792. this._animate();
  27793. this.onAfterAnimationsObservable.notifyObservers(this);
  27794. // Physics
  27795. if (this._physicsEngine) {
  27796. this.onBeforePhysicsObservable.notifyObservers(this);
  27797. this._physicsEngine._step(defaultFrameTime / 1000);
  27798. this.onAfterPhysicsObservable.notifyObservers(this);
  27799. }
  27800. this.onAfterStepObservable.notifyObservers(this);
  27801. this._currentStepId++;
  27802. stepsTaken++;
  27803. deltaTime -= defaultFrameTime;
  27804. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27805. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27806. }
  27807. else {
  27808. // Animations
  27809. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27810. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27811. this._animate();
  27812. this.onAfterAnimationsObservable.notifyObservers(this);
  27813. // Physics
  27814. if (this._physicsEngine) {
  27815. this.onBeforePhysicsObservable.notifyObservers(this);
  27816. this._physicsEngine._step(deltaTime / 1000.0);
  27817. this.onAfterPhysicsObservable.notifyObservers(this);
  27818. }
  27819. }
  27820. // update gamepad manager
  27821. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27822. this._gamepadManager._checkGamepadsStatus();
  27823. }
  27824. // Update Cameras
  27825. if (updateCameras) {
  27826. if (this.activeCameras.length > 0) {
  27827. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27828. var camera = this.activeCameras[cameraIndex];
  27829. camera.update();
  27830. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27831. // rig cameras
  27832. for (var index = 0; index < camera._rigCameras.length; index++) {
  27833. camera._rigCameras[index].update();
  27834. }
  27835. }
  27836. }
  27837. }
  27838. else if (this.activeCamera) {
  27839. this.activeCamera.update();
  27840. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27841. // rig cameras
  27842. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27843. this.activeCamera._rigCameras[index].update();
  27844. }
  27845. }
  27846. }
  27847. }
  27848. // Before render
  27849. this.onBeforeRenderObservable.notifyObservers(this);
  27850. // Customs render targets
  27851. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27852. var engine = this.getEngine();
  27853. var currentActiveCamera = this.activeCamera;
  27854. if (this.renderTargetsEnabled) {
  27855. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27856. this._intermediateRendering = true;
  27857. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27858. var renderTarget = this.customRenderTargets[customIndex];
  27859. if (renderTarget._shouldRender()) {
  27860. this._renderId++;
  27861. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27862. if (!this.activeCamera)
  27863. throw new Error("Active camera not set");
  27864. // Viewport
  27865. engine.setViewport(this.activeCamera.viewport);
  27866. // Camera
  27867. this.updateTransformMatrix();
  27868. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27869. }
  27870. }
  27871. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27872. this._intermediateRendering = false;
  27873. this._renderId++;
  27874. }
  27875. // Restore back buffer
  27876. if (this.customRenderTargets.length > 0) {
  27877. engine.restoreDefaultFramebuffer();
  27878. }
  27879. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27880. this.activeCamera = currentActiveCamera;
  27881. // Procedural textures
  27882. if (this.proceduralTexturesEnabled) {
  27883. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27884. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27885. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27886. if (proceduralTexture._shouldRender()) {
  27887. proceduralTexture.render();
  27888. }
  27889. }
  27890. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27891. }
  27892. // Clear
  27893. if (this.autoClearDepthAndStencil || this.autoClear) {
  27894. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27895. }
  27896. // Shadows
  27897. if (this.shadowsEnabled) {
  27898. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27899. var light = this.lights[lightIndex];
  27900. var shadowGenerator = light.getShadowGenerator();
  27901. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27902. var shadowMap = (shadowGenerator.getShadowMap());
  27903. if (this.textures.indexOf(shadowMap) !== -1) {
  27904. this._renderTargets.push(shadowMap);
  27905. }
  27906. }
  27907. }
  27908. }
  27909. // Depth renderer
  27910. for (var key in this._depthRenderer) {
  27911. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27912. }
  27913. // Geometry renderer
  27914. if (this._geometryBufferRenderer) {
  27915. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27916. }
  27917. // RenderPipeline
  27918. if (this._postProcessRenderPipelineManager) {
  27919. this._postProcessRenderPipelineManager.update();
  27920. }
  27921. // Multi-cameras?
  27922. if (this.activeCameras.length > 0) {
  27923. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27924. if (cameraIndex > 0) {
  27925. this._engine.clear(null, false, true, true);
  27926. }
  27927. this._processSubCameras(this.activeCameras[cameraIndex]);
  27928. }
  27929. }
  27930. else {
  27931. if (!this.activeCamera) {
  27932. throw new Error("No camera defined");
  27933. }
  27934. this._processSubCameras(this.activeCamera);
  27935. }
  27936. // Intersection checks
  27937. this._checkIntersections();
  27938. // Update the audio listener attached to the camera
  27939. if (BABYLON.AudioEngine) {
  27940. this._updateAudioParameters();
  27941. }
  27942. // After render
  27943. if (this.afterRender) {
  27944. this.afterRender();
  27945. }
  27946. this.onAfterRenderObservable.notifyObservers(this);
  27947. // Cleaning
  27948. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27949. var data = this._toBeDisposed.data[index];
  27950. if (data) {
  27951. data.dispose();
  27952. }
  27953. this._toBeDisposed[index] = null;
  27954. }
  27955. this._toBeDisposed.reset();
  27956. if (this.dumpNextRenderTargets) {
  27957. this.dumpNextRenderTargets = false;
  27958. }
  27959. this._activeBones.addCount(0, true);
  27960. this._activeIndices.addCount(0, true);
  27961. this._activeParticles.addCount(0, true);
  27962. };
  27963. Scene.prototype._updateAudioParameters = function () {
  27964. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27965. return;
  27966. }
  27967. var listeningCamera;
  27968. var audioEngine = BABYLON.Engine.audioEngine;
  27969. if (this.activeCameras.length > 0) {
  27970. listeningCamera = this.activeCameras[0];
  27971. }
  27972. else {
  27973. listeningCamera = this.activeCamera;
  27974. }
  27975. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27976. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27977. // for VR cameras
  27978. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27979. listeningCamera = listeningCamera.rigCameras[0];
  27980. }
  27981. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27982. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27983. cameraDirection.normalize();
  27984. // To avoid some errors on GearVR
  27985. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27986. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27987. }
  27988. var i;
  27989. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27990. var sound = this.mainSoundTrack.soundCollection[i];
  27991. if (sound.useCustomAttenuation) {
  27992. sound.updateDistanceFromListener();
  27993. }
  27994. }
  27995. for (i = 0; i < this.soundTracks.length; i++) {
  27996. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27997. sound = this.soundTracks[i].soundCollection[j];
  27998. if (sound.useCustomAttenuation) {
  27999. sound.updateDistanceFromListener();
  28000. }
  28001. }
  28002. }
  28003. }
  28004. };
  28005. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28006. // Audio
  28007. /**
  28008. * Gets or sets if audio support is enabled
  28009. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28010. */
  28011. get: function () {
  28012. return this._audioEnabled;
  28013. },
  28014. set: function (value) {
  28015. this._audioEnabled = value;
  28016. if (BABYLON.AudioEngine) {
  28017. if (this._audioEnabled) {
  28018. this._enableAudio();
  28019. }
  28020. else {
  28021. this._disableAudio();
  28022. }
  28023. }
  28024. },
  28025. enumerable: true,
  28026. configurable: true
  28027. });
  28028. Scene.prototype._disableAudio = function () {
  28029. var i;
  28030. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28031. this.mainSoundTrack.soundCollection[i].pause();
  28032. }
  28033. for (i = 0; i < this.soundTracks.length; i++) {
  28034. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28035. this.soundTracks[i].soundCollection[j].pause();
  28036. }
  28037. }
  28038. };
  28039. Scene.prototype._enableAudio = function () {
  28040. var i;
  28041. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28042. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28043. this.mainSoundTrack.soundCollection[i].play();
  28044. }
  28045. }
  28046. for (i = 0; i < this.soundTracks.length; i++) {
  28047. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28048. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28049. this.soundTracks[i].soundCollection[j].play();
  28050. }
  28051. }
  28052. }
  28053. };
  28054. Object.defineProperty(Scene.prototype, "headphone", {
  28055. /**
  28056. * Gets or sets if audio will be output to headphones
  28057. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28058. */
  28059. get: function () {
  28060. return this._headphone;
  28061. },
  28062. set: function (value) {
  28063. this._headphone = value;
  28064. if (BABYLON.AudioEngine) {
  28065. if (this._headphone) {
  28066. this._switchAudioModeForHeadphones();
  28067. }
  28068. else {
  28069. this._switchAudioModeForNormalSpeakers();
  28070. }
  28071. }
  28072. },
  28073. enumerable: true,
  28074. configurable: true
  28075. });
  28076. Scene.prototype._switchAudioModeForHeadphones = function () {
  28077. this.mainSoundTrack.switchPanningModelToHRTF();
  28078. for (var i = 0; i < this.soundTracks.length; i++) {
  28079. this.soundTracks[i].switchPanningModelToHRTF();
  28080. }
  28081. };
  28082. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28083. this.mainSoundTrack.switchPanningModelToEqualPower();
  28084. for (var i = 0; i < this.soundTracks.length; i++) {
  28085. this.soundTracks[i].switchPanningModelToEqualPower();
  28086. }
  28087. };
  28088. /**
  28089. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28090. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28091. * @returns the created depth renderer
  28092. */
  28093. Scene.prototype.enableDepthRenderer = function (camera) {
  28094. camera = camera || this.activeCamera;
  28095. if (!camera) {
  28096. throw "No camera available to enable depth renderer";
  28097. }
  28098. if (!this._depthRenderer[camera.id]) {
  28099. var textureType = 0;
  28100. if (this._engine.getCaps().textureHalfFloatRender) {
  28101. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28102. }
  28103. else if (this._engine.getCaps().textureFloatRender) {
  28104. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28105. }
  28106. else {
  28107. throw "Depth renderer does not support int texture type";
  28108. }
  28109. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28110. }
  28111. return this._depthRenderer[camera.id];
  28112. };
  28113. /**
  28114. * Disables a depth renderer for a given camera
  28115. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28116. */
  28117. Scene.prototype.disableDepthRenderer = function (camera) {
  28118. camera = camera || this.activeCamera;
  28119. if (!camera || !this._depthRenderer[camera.id]) {
  28120. return;
  28121. }
  28122. this._depthRenderer[camera.id].dispose();
  28123. delete this._depthRenderer[camera.id];
  28124. };
  28125. /**
  28126. * Enables a GeometryBufferRender and associates it with the scene
  28127. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28128. * @returns the GeometryBufferRenderer
  28129. */
  28130. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28131. if (ratio === void 0) { ratio = 1; }
  28132. if (this._geometryBufferRenderer) {
  28133. return this._geometryBufferRenderer;
  28134. }
  28135. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28136. if (!this._geometryBufferRenderer.isSupported) {
  28137. this._geometryBufferRenderer = null;
  28138. }
  28139. return this._geometryBufferRenderer;
  28140. };
  28141. /**
  28142. * Disables the GeometryBufferRender associated with the scene
  28143. */
  28144. Scene.prototype.disableGeometryBufferRenderer = function () {
  28145. if (!this._geometryBufferRenderer) {
  28146. return;
  28147. }
  28148. this._geometryBufferRenderer.dispose();
  28149. this._geometryBufferRenderer = null;
  28150. };
  28151. /**
  28152. * Freeze all materials
  28153. * A frozen material will not be updatable but should be faster to render
  28154. */
  28155. Scene.prototype.freezeMaterials = function () {
  28156. for (var i = 0; i < this.materials.length; i++) {
  28157. this.materials[i].freeze();
  28158. }
  28159. };
  28160. /**
  28161. * Unfreeze all materials
  28162. * A frozen material will not be updatable but should be faster to render
  28163. */
  28164. Scene.prototype.unfreezeMaterials = function () {
  28165. for (var i = 0; i < this.materials.length; i++) {
  28166. this.materials[i].unfreeze();
  28167. }
  28168. };
  28169. /**
  28170. * Releases all held ressources
  28171. */
  28172. Scene.prototype.dispose = function () {
  28173. this.beforeRender = null;
  28174. this.afterRender = null;
  28175. this.skeletons = [];
  28176. this.morphTargetManagers = [];
  28177. this.importedMeshesFiles = new Array();
  28178. this.stopAllAnimations();
  28179. this.resetCachedMaterial();
  28180. for (var key in this._depthRenderer) {
  28181. this._depthRenderer[key].dispose();
  28182. }
  28183. if (this._gamepadManager) {
  28184. this._gamepadManager.dispose();
  28185. this._gamepadManager = null;
  28186. }
  28187. // Smart arrays
  28188. if (this.activeCamera) {
  28189. this.activeCamera._activeMeshes.dispose();
  28190. this.activeCamera = null;
  28191. }
  28192. this._activeMeshes.dispose();
  28193. this._renderingManager.dispose();
  28194. this._processedMaterials.dispose();
  28195. this._activeParticleSystems.dispose();
  28196. this._activeSkeletons.dispose();
  28197. this._softwareSkinnedMeshes.dispose();
  28198. this._renderTargets.dispose();
  28199. this._registeredForLateAnimationBindings.dispose();
  28200. if (this._boundingBoxRenderer) {
  28201. this._boundingBoxRenderer.dispose();
  28202. }
  28203. this._meshesForIntersections.dispose();
  28204. this._toBeDisposed.dispose();
  28205. // Abort active requests
  28206. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28207. var request = _a[_i];
  28208. request.abort();
  28209. }
  28210. // Debug layer
  28211. if (this._debugLayer) {
  28212. this._debugLayer.hide();
  28213. }
  28214. // Events
  28215. this.onDisposeObservable.notifyObservers(this);
  28216. this.onDisposeObservable.clear();
  28217. this.onBeforeRenderObservable.clear();
  28218. this.onAfterRenderObservable.clear();
  28219. this.onBeforeRenderTargetsRenderObservable.clear();
  28220. this.onAfterRenderTargetsRenderObservable.clear();
  28221. this.onAfterStepObservable.clear();
  28222. this.onBeforeStepObservable.clear();
  28223. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28224. this.onAfterActiveMeshesEvaluationObservable.clear();
  28225. this.onBeforeParticlesRenderingObservable.clear();
  28226. this.onAfterParticlesRenderingObservable.clear();
  28227. this.onBeforeSpritesRenderingObservable.clear();
  28228. this.onAfterSpritesRenderingObservable.clear();
  28229. this.onBeforeDrawPhaseObservable.clear();
  28230. this.onAfterDrawPhaseObservable.clear();
  28231. this.onBeforePhysicsObservable.clear();
  28232. this.onAfterPhysicsObservable.clear();
  28233. this.onBeforeAnimationsObservable.clear();
  28234. this.onAfterAnimationsObservable.clear();
  28235. this.onDataLoadedObservable.clear();
  28236. this.detachControl();
  28237. // Release sounds & sounds tracks
  28238. if (BABYLON.AudioEngine) {
  28239. this.disposeSounds();
  28240. }
  28241. // VR Helper
  28242. if (this.VRHelper) {
  28243. this.VRHelper.dispose();
  28244. }
  28245. // Detach cameras
  28246. var canvas = this._engine.getRenderingCanvas();
  28247. if (canvas) {
  28248. var index;
  28249. for (index = 0; index < this.cameras.length; index++) {
  28250. this.cameras[index].detachControl(canvas);
  28251. }
  28252. }
  28253. // Release animation groups
  28254. while (this.animationGroups.length) {
  28255. this.animationGroups[0].dispose();
  28256. }
  28257. // Release lights
  28258. while (this.lights.length) {
  28259. this.lights[0].dispose();
  28260. }
  28261. // Release meshes
  28262. while (this.meshes.length) {
  28263. this.meshes[0].dispose(true);
  28264. }
  28265. while (this.transformNodes.length) {
  28266. this.removeTransformNode(this.transformNodes[0]);
  28267. }
  28268. // Release cameras
  28269. while (this.cameras.length) {
  28270. this.cameras[0].dispose();
  28271. }
  28272. // Release materials
  28273. if (this.defaultMaterial) {
  28274. this.defaultMaterial.dispose();
  28275. }
  28276. while (this.multiMaterials.length) {
  28277. this.multiMaterials[0].dispose();
  28278. }
  28279. while (this.materials.length) {
  28280. this.materials[0].dispose();
  28281. }
  28282. // Release particles
  28283. while (this.particleSystems.length) {
  28284. this.particleSystems[0].dispose();
  28285. }
  28286. // Release sprites
  28287. while (this.spriteManagers.length) {
  28288. this.spriteManagers[0].dispose();
  28289. }
  28290. // Release postProcesses
  28291. while (this.postProcesses.length) {
  28292. this.postProcesses[0].dispose();
  28293. }
  28294. // Release layers
  28295. while (this.layers.length) {
  28296. this.layers[0].dispose();
  28297. }
  28298. while (this.effectLayers.length) {
  28299. this.effectLayers[0].dispose();
  28300. }
  28301. // Release textures
  28302. while (this.textures.length) {
  28303. this.textures[0].dispose();
  28304. }
  28305. // Release UBO
  28306. this._sceneUbo.dispose();
  28307. if (this._alternateSceneUbo) {
  28308. this._alternateSceneUbo.dispose();
  28309. }
  28310. // Post-processes
  28311. this.postProcessManager.dispose();
  28312. if (this._postProcessRenderPipelineManager) {
  28313. this._postProcessRenderPipelineManager.dispose();
  28314. }
  28315. // Physics
  28316. if (this._physicsEngine) {
  28317. this.disablePhysicsEngine();
  28318. }
  28319. // Remove from engine
  28320. index = this._engine.scenes.indexOf(this);
  28321. if (index > -1) {
  28322. this._engine.scenes.splice(index, 1);
  28323. }
  28324. this._engine.wipeCaches(true);
  28325. this._isDisposed = true;
  28326. };
  28327. Object.defineProperty(Scene.prototype, "isDisposed", {
  28328. /**
  28329. * Gets if the scene is already disposed
  28330. */
  28331. get: function () {
  28332. return this._isDisposed;
  28333. },
  28334. enumerable: true,
  28335. configurable: true
  28336. });
  28337. /**
  28338. * Releases sounds & soundtracks
  28339. */
  28340. Scene.prototype.disposeSounds = function () {
  28341. if (!this._mainSoundTrack) {
  28342. return;
  28343. }
  28344. this.mainSoundTrack.dispose();
  28345. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28346. this.soundTracks[scIndex].dispose();
  28347. }
  28348. };
  28349. /**
  28350. * Call this function to reduce memory footprint of the scene.
  28351. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28352. */
  28353. Scene.prototype.clearCachedVertexData = function () {
  28354. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28355. var mesh = this.meshes[meshIndex];
  28356. var geometry = mesh.geometry;
  28357. if (geometry) {
  28358. geometry._indices = [];
  28359. for (var vbName in geometry._vertexBuffers) {
  28360. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28361. continue;
  28362. }
  28363. geometry._vertexBuffers[vbName]._buffer._data = null;
  28364. }
  28365. }
  28366. }
  28367. };
  28368. /**
  28369. * This function will remove the local cached buffer data from texture.
  28370. * It will save memory but will prevent the texture from being rebuilt
  28371. */
  28372. Scene.prototype.cleanCachedTextureBuffer = function () {
  28373. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28374. var baseTexture = _a[_i];
  28375. var buffer = baseTexture._buffer;
  28376. if (buffer) {
  28377. baseTexture._buffer = null;
  28378. }
  28379. }
  28380. };
  28381. // Octrees
  28382. /**
  28383. * Get the world extend vectors with an optional filter
  28384. *
  28385. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28386. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28387. */
  28388. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28389. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28390. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28391. filterPredicate = filterPredicate || (function () { return true; });
  28392. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28393. mesh.computeWorldMatrix(true);
  28394. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28395. return;
  28396. }
  28397. var boundingInfo = mesh.getBoundingInfo();
  28398. var minBox = boundingInfo.boundingBox.minimumWorld;
  28399. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28400. BABYLON.Tools.CheckExtends(minBox, min, max);
  28401. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28402. });
  28403. return {
  28404. min: min,
  28405. max: max
  28406. };
  28407. };
  28408. /**
  28409. * Creates or updates the octree used to boost selection (picking)
  28410. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28411. * @param maxCapacity defines the maximum capacity per leaf
  28412. * @param maxDepth defines the maximum depth of the octree
  28413. * @returns an octree of AbstractMesh
  28414. */
  28415. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28416. if (maxCapacity === void 0) { maxCapacity = 64; }
  28417. if (maxDepth === void 0) { maxDepth = 2; }
  28418. if (!this._selectionOctree) {
  28419. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28420. }
  28421. var worldExtends = this.getWorldExtends();
  28422. // Update octree
  28423. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28424. return this._selectionOctree;
  28425. };
  28426. // Picking
  28427. /**
  28428. * Creates a ray that can be used to pick in the scene
  28429. * @param x defines the x coordinate of the origin (on-screen)
  28430. * @param y defines the y coordinate of the origin (on-screen)
  28431. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28432. * @param camera defines the camera to use for the picking
  28433. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28434. * @returns a Ray
  28435. */
  28436. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28437. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28438. var result = BABYLON.Ray.Zero();
  28439. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28440. return result;
  28441. };
  28442. /**
  28443. * Creates a ray that can be used to pick in the scene
  28444. * @param x defines the x coordinate of the origin (on-screen)
  28445. * @param y defines the y coordinate of the origin (on-screen)
  28446. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28447. * @param result defines the ray where to store the picking ray
  28448. * @param camera defines the camera to use for the picking
  28449. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28450. * @returns the current scene
  28451. */
  28452. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28453. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28454. var engine = this._engine;
  28455. if (!camera) {
  28456. if (!this.activeCamera)
  28457. throw new Error("Active camera not set");
  28458. camera = this.activeCamera;
  28459. }
  28460. var cameraViewport = camera.viewport;
  28461. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28462. // Moving coordinates to local viewport world
  28463. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28464. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28465. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28466. return this;
  28467. };
  28468. /**
  28469. * Creates a ray that can be used to pick in the scene
  28470. * @param x defines the x coordinate of the origin (on-screen)
  28471. * @param y defines the y coordinate of the origin (on-screen)
  28472. * @param camera defines the camera to use for the picking
  28473. * @returns a Ray
  28474. */
  28475. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28476. var result = BABYLON.Ray.Zero();
  28477. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28478. return result;
  28479. };
  28480. /**
  28481. * Creates a ray that can be used to pick in the scene
  28482. * @param x defines the x coordinate of the origin (on-screen)
  28483. * @param y defines the y coordinate of the origin (on-screen)
  28484. * @param result defines the ray where to store the picking ray
  28485. * @param camera defines the camera to use for the picking
  28486. * @returns the current scene
  28487. */
  28488. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28489. if (!BABYLON.PickingInfo) {
  28490. return this;
  28491. }
  28492. var engine = this._engine;
  28493. if (!camera) {
  28494. if (!this.activeCamera)
  28495. throw new Error("Active camera not set");
  28496. camera = this.activeCamera;
  28497. }
  28498. var cameraViewport = camera.viewport;
  28499. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28500. var identity = BABYLON.Matrix.Identity();
  28501. // Moving coordinates to local viewport world
  28502. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28503. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28504. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28505. return this;
  28506. };
  28507. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28508. if (!BABYLON.PickingInfo) {
  28509. return null;
  28510. }
  28511. var pickingInfo = null;
  28512. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28513. var mesh = this.meshes[meshIndex];
  28514. if (predicate) {
  28515. if (!predicate(mesh)) {
  28516. continue;
  28517. }
  28518. }
  28519. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28520. continue;
  28521. }
  28522. var world = mesh.getWorldMatrix();
  28523. var ray = rayFunction(world);
  28524. var result = mesh.intersects(ray, fastCheck);
  28525. if (!result || !result.hit)
  28526. continue;
  28527. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28528. continue;
  28529. pickingInfo = result;
  28530. if (fastCheck) {
  28531. break;
  28532. }
  28533. }
  28534. return pickingInfo || new BABYLON.PickingInfo();
  28535. };
  28536. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28537. if (!BABYLON.PickingInfo) {
  28538. return null;
  28539. }
  28540. var pickingInfos = new Array();
  28541. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28542. var mesh = this.meshes[meshIndex];
  28543. if (predicate) {
  28544. if (!predicate(mesh)) {
  28545. continue;
  28546. }
  28547. }
  28548. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28549. continue;
  28550. }
  28551. var world = mesh.getWorldMatrix();
  28552. var ray = rayFunction(world);
  28553. var result = mesh.intersects(ray, false);
  28554. if (!result || !result.hit)
  28555. continue;
  28556. pickingInfos.push(result);
  28557. }
  28558. return pickingInfos;
  28559. };
  28560. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28561. if (!BABYLON.PickingInfo) {
  28562. return null;
  28563. }
  28564. var pickingInfo = null;
  28565. if (!camera) {
  28566. if (!this.activeCamera) {
  28567. return null;
  28568. }
  28569. camera = this.activeCamera;
  28570. }
  28571. if (this.spriteManagers.length > 0) {
  28572. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28573. var spriteManager = this.spriteManagers[spriteIndex];
  28574. if (!spriteManager.isPickable) {
  28575. continue;
  28576. }
  28577. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28578. if (!result || !result.hit)
  28579. continue;
  28580. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28581. continue;
  28582. pickingInfo = result;
  28583. if (fastCheck) {
  28584. break;
  28585. }
  28586. }
  28587. }
  28588. return pickingInfo || new BABYLON.PickingInfo();
  28589. };
  28590. /** Launch a ray to try to pick a mesh in the scene
  28591. * @param x position on screen
  28592. * @param y position on screen
  28593. * @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
  28594. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28595. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28596. * @returns a PickingInfo
  28597. */
  28598. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28599. var _this = this;
  28600. if (!BABYLON.PickingInfo) {
  28601. return null;
  28602. }
  28603. var result = this._internalPick(function (world) {
  28604. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28605. return _this._tempPickingRay;
  28606. }, predicate, fastCheck);
  28607. if (result) {
  28608. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28609. }
  28610. return result;
  28611. };
  28612. /** Launch a ray to try to pick a sprite in the scene
  28613. * @param x position on screen
  28614. * @param y position on screen
  28615. * @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
  28616. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28617. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28618. * @returns a PickingInfo
  28619. */
  28620. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28621. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28622. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28623. };
  28624. /** Use the given ray to pick a mesh in the scene
  28625. * @param ray The ray to use to pick meshes
  28626. * @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
  28627. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28628. * @returns a PickingInfo
  28629. */
  28630. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28631. var _this = this;
  28632. var result = this._internalPick(function (world) {
  28633. if (!_this._pickWithRayInverseMatrix) {
  28634. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28635. }
  28636. world.invertToRef(_this._pickWithRayInverseMatrix);
  28637. if (!_this._cachedRayForTransform) {
  28638. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28639. }
  28640. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28641. return _this._cachedRayForTransform;
  28642. }, predicate, fastCheck);
  28643. if (result) {
  28644. result.ray = ray;
  28645. }
  28646. return result;
  28647. };
  28648. /**
  28649. * Launch a ray to try to pick a mesh in the scene
  28650. * @param x X position on screen
  28651. * @param y Y position on screen
  28652. * @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
  28653. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28654. * @returns an array of PickingInfo
  28655. */
  28656. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28657. var _this = this;
  28658. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28659. };
  28660. /**
  28661. * Launch a ray to try to pick a mesh in the scene
  28662. * @param ray Ray to use
  28663. * @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
  28664. * @returns an array of PickingInfo
  28665. */
  28666. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28667. var _this = this;
  28668. return this._internalMultiPick(function (world) {
  28669. if (!_this._pickWithRayInverseMatrix) {
  28670. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28671. }
  28672. world.invertToRef(_this._pickWithRayInverseMatrix);
  28673. if (!_this._cachedRayForTransform) {
  28674. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28675. }
  28676. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28677. return _this._cachedRayForTransform;
  28678. }, predicate);
  28679. };
  28680. /**
  28681. * Force the value of meshUnderPointer
  28682. * @param mesh defines the mesh to use
  28683. */
  28684. Scene.prototype.setPointerOverMesh = function (mesh) {
  28685. if (this._pointerOverMesh === mesh) {
  28686. return;
  28687. }
  28688. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28689. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28690. }
  28691. this._pointerOverMesh = mesh;
  28692. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28693. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28694. }
  28695. };
  28696. /**
  28697. * Gets the mesh under the pointer
  28698. * @returns a Mesh or null if no mesh is under the pointer
  28699. */
  28700. Scene.prototype.getPointerOverMesh = function () {
  28701. return this._pointerOverMesh;
  28702. };
  28703. /**
  28704. * Force the sprite under the pointer
  28705. * @param sprite defines the sprite to use
  28706. */
  28707. Scene.prototype.setPointerOverSprite = function (sprite) {
  28708. if (this._pointerOverSprite === sprite) {
  28709. return;
  28710. }
  28711. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28712. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28713. }
  28714. this._pointerOverSprite = sprite;
  28715. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28716. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28717. }
  28718. };
  28719. /**
  28720. * Gets the sprite under the pointer
  28721. * @returns a Sprite or null if no sprite is under the pointer
  28722. */
  28723. Scene.prototype.getPointerOverSprite = function () {
  28724. return this._pointerOverSprite;
  28725. };
  28726. // Physics
  28727. /**
  28728. * Gets the current physics engine
  28729. * @returns a PhysicsEngine or null if none attached
  28730. */
  28731. Scene.prototype.getPhysicsEngine = function () {
  28732. return this._physicsEngine;
  28733. };
  28734. /**
  28735. * Enables physics to the current scene
  28736. * @param gravity defines the scene's gravity for the physics engine
  28737. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28738. * @return a boolean indicating if the physics engine was initialized
  28739. */
  28740. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28741. if (gravity === void 0) { gravity = null; }
  28742. if (this._physicsEngine) {
  28743. return true;
  28744. }
  28745. try {
  28746. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28747. return true;
  28748. }
  28749. catch (e) {
  28750. BABYLON.Tools.Error(e.message);
  28751. return false;
  28752. }
  28753. };
  28754. /**
  28755. * Disables and disposes the physics engine associated with the scene
  28756. */
  28757. Scene.prototype.disablePhysicsEngine = function () {
  28758. if (!this._physicsEngine) {
  28759. return;
  28760. }
  28761. this._physicsEngine.dispose();
  28762. this._physicsEngine = null;
  28763. };
  28764. /**
  28765. * Gets a boolean indicating if there is an active physics engine
  28766. * @returns a boolean indicating if there is an active physics engine
  28767. */
  28768. Scene.prototype.isPhysicsEnabled = function () {
  28769. return this._physicsEngine !== undefined;
  28770. };
  28771. /**
  28772. * Deletes a physics compound impostor
  28773. * @param compound defines the compound to delete
  28774. */
  28775. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28776. var mesh = compound.parts[0].mesh;
  28777. if (mesh.physicsImpostor) {
  28778. mesh.physicsImpostor.dispose( /*true*/);
  28779. mesh.physicsImpostor = null;
  28780. }
  28781. };
  28782. // Misc.
  28783. /** @hidden */
  28784. Scene.prototype._rebuildGeometries = function () {
  28785. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28786. var geometry = _a[_i];
  28787. geometry._rebuild();
  28788. }
  28789. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28790. var mesh = _c[_b];
  28791. mesh._rebuild();
  28792. }
  28793. if (this.postProcessManager) {
  28794. this.postProcessManager._rebuild();
  28795. }
  28796. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28797. var layer = _e[_d];
  28798. layer._rebuild();
  28799. }
  28800. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28801. var effectLayer = _g[_f];
  28802. effectLayer._rebuild();
  28803. }
  28804. if (this._boundingBoxRenderer) {
  28805. this._boundingBoxRenderer._rebuild();
  28806. }
  28807. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28808. var system = _j[_h];
  28809. system.rebuild();
  28810. }
  28811. if (this._postProcessRenderPipelineManager) {
  28812. this._postProcessRenderPipelineManager._rebuild();
  28813. }
  28814. };
  28815. /** @hidden */
  28816. Scene.prototype._rebuildTextures = function () {
  28817. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28818. var texture = _a[_i];
  28819. texture._rebuild();
  28820. }
  28821. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28822. };
  28823. /**
  28824. * Creates a default light for the scene.
  28825. * @param replace Whether to replace the existing lights in the scene.
  28826. */
  28827. Scene.prototype.createDefaultLight = function (replace) {
  28828. if (replace === void 0) { replace = false; }
  28829. // Dispose existing light in replace mode.
  28830. if (replace) {
  28831. if (this.lights) {
  28832. for (var i = 0; i < this.lights.length; i++) {
  28833. this.lights[i].dispose();
  28834. }
  28835. }
  28836. }
  28837. // Light
  28838. if (this.lights.length === 0) {
  28839. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28840. }
  28841. };
  28842. /**
  28843. * Creates a default camera for the scene.
  28844. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28845. * @param replace Whether to replace the existing active camera in the scene.
  28846. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28847. */
  28848. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28849. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28850. if (replace === void 0) { replace = false; }
  28851. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28852. // Dispose existing camera in replace mode.
  28853. if (replace) {
  28854. if (this.activeCamera) {
  28855. this.activeCamera.dispose();
  28856. this.activeCamera = null;
  28857. }
  28858. }
  28859. // Camera
  28860. if (!this.activeCamera) {
  28861. var worldExtends = this.getWorldExtends();
  28862. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28863. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28864. var camera;
  28865. var radius = worldSize.length() * 1.5;
  28866. // empty scene scenario!
  28867. if (!isFinite(radius)) {
  28868. radius = 1;
  28869. worldCenter.copyFromFloats(0, 0, 0);
  28870. }
  28871. if (createArcRotateCamera) {
  28872. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28873. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28874. arcRotateCamera.wheelPrecision = 100 / radius;
  28875. camera = arcRotateCamera;
  28876. }
  28877. else {
  28878. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28879. freeCamera.setTarget(worldCenter);
  28880. camera = freeCamera;
  28881. }
  28882. camera.minZ = radius * 0.01;
  28883. camera.maxZ = radius * 1000;
  28884. camera.speed = radius * 0.2;
  28885. this.activeCamera = camera;
  28886. var canvas = this.getEngine().getRenderingCanvas();
  28887. if (attachCameraControls && canvas) {
  28888. camera.attachControl(canvas);
  28889. }
  28890. }
  28891. };
  28892. /**
  28893. * Creates a default camera and a default light
  28894. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28895. * @param replace defines if the camera and/or light will replace the existing ones
  28896. * @param attachCameraControls defines if attachControl will be called on the new camera
  28897. */
  28898. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28899. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28900. if (replace === void 0) { replace = false; }
  28901. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28902. this.createDefaultLight(replace);
  28903. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28904. };
  28905. /**
  28906. * Creates a new sky box
  28907. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28908. * @param environmentTexture defines the texture to use as environment texture
  28909. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28910. * @param scale defines the overall scale of the skybox
  28911. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28912. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28913. * @returns a new mesh holding the sky box
  28914. */
  28915. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28916. if (pbr === void 0) { pbr = false; }
  28917. if (scale === void 0) { scale = 1000; }
  28918. if (blur === void 0) { blur = 0; }
  28919. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28920. if (!environmentTexture) {
  28921. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28922. return null;
  28923. }
  28924. if (setGlobalEnvTexture) {
  28925. if (environmentTexture) {
  28926. this.environmentTexture = environmentTexture;
  28927. }
  28928. }
  28929. // Skybox
  28930. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28931. if (pbr) {
  28932. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28933. hdrSkyboxMaterial.backFaceCulling = false;
  28934. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28935. if (hdrSkyboxMaterial.reflectionTexture) {
  28936. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28937. }
  28938. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28939. hdrSkyboxMaterial.disableLighting = true;
  28940. hdrSkyboxMaterial.twoSidedLighting = true;
  28941. hdrSkybox.infiniteDistance = true;
  28942. hdrSkybox.material = hdrSkyboxMaterial;
  28943. }
  28944. else {
  28945. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28946. skyboxMaterial.backFaceCulling = false;
  28947. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28948. if (skyboxMaterial.reflectionTexture) {
  28949. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28950. }
  28951. skyboxMaterial.disableLighting = true;
  28952. hdrSkybox.infiniteDistance = true;
  28953. hdrSkybox.material = skyboxMaterial;
  28954. }
  28955. return hdrSkybox;
  28956. };
  28957. /**
  28958. * Creates a new environment
  28959. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28960. * @param options defines the options you can use to configure the environment
  28961. * @returns the new EnvironmentHelper
  28962. */
  28963. Scene.prototype.createDefaultEnvironment = function (options) {
  28964. if (BABYLON.EnvironmentHelper) {
  28965. return new BABYLON.EnvironmentHelper(options, this);
  28966. }
  28967. return null;
  28968. };
  28969. /**
  28970. * Creates a new VREXperienceHelper
  28971. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28972. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28973. * @returns a new VREXperienceHelper
  28974. */
  28975. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28976. if (webVROptions === void 0) { webVROptions = {}; }
  28977. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28978. };
  28979. // Tags
  28980. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28981. if (tagsQuery === undefined) {
  28982. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28983. return list;
  28984. }
  28985. var listByTags = [];
  28986. forEach = forEach || (function (item) { return; });
  28987. for (var i in list) {
  28988. var item = list[i];
  28989. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28990. listByTags.push(item);
  28991. forEach(item);
  28992. }
  28993. }
  28994. return listByTags;
  28995. };
  28996. /**
  28997. * Get a list of meshes by tags
  28998. * @param tagsQuery defines the tags query to use
  28999. * @param forEach defines a predicate used to filter results
  29000. * @returns an array of Mesh
  29001. */
  29002. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29003. return this._getByTags(this.meshes, tagsQuery, forEach);
  29004. };
  29005. /**
  29006. * Get a list of cameras by tags
  29007. * @param tagsQuery defines the tags query to use
  29008. * @param forEach defines a predicate used to filter results
  29009. * @returns an array of Camera
  29010. */
  29011. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29012. return this._getByTags(this.cameras, tagsQuery, forEach);
  29013. };
  29014. /**
  29015. * Get a list of lights by tags
  29016. * @param tagsQuery defines the tags query to use
  29017. * @param forEach defines a predicate used to filter results
  29018. * @returns an array of Light
  29019. */
  29020. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29021. return this._getByTags(this.lights, tagsQuery, forEach);
  29022. };
  29023. /**
  29024. * Get a list of materials by tags
  29025. * @param tagsQuery defines the tags query to use
  29026. * @param forEach defines a predicate used to filter results
  29027. * @returns an array of Material
  29028. */
  29029. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29030. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29031. };
  29032. /**
  29033. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29034. * This allowed control for front to back rendering or reversly depending of the special needs.
  29035. *
  29036. * @param renderingGroupId The rendering group id corresponding to its index
  29037. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29038. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29039. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29040. */
  29041. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29042. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29043. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29044. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29045. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29046. };
  29047. /**
  29048. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29049. *
  29050. * @param renderingGroupId The rendering group id corresponding to its index
  29051. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29052. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29053. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29054. */
  29055. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29056. if (depth === void 0) { depth = true; }
  29057. if (stencil === void 0) { stencil = true; }
  29058. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29059. };
  29060. /**
  29061. * Will flag all materials as dirty to trigger new shader compilation
  29062. * @param flag defines the flag used to specify which material part must be marked as dirty
  29063. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29064. */
  29065. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29066. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29067. var material = _a[_i];
  29068. if (predicate && !predicate(material)) {
  29069. continue;
  29070. }
  29071. material.markAsDirty(flag);
  29072. }
  29073. };
  29074. /** @hidden */
  29075. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29076. var _this = this;
  29077. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29078. this._activeRequests.push(request);
  29079. request.onCompleteObservable.add(function (request) {
  29080. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29081. });
  29082. return request;
  29083. };
  29084. /** @hidden */
  29085. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29086. var _this = this;
  29087. return new Promise(function (resolve, reject) {
  29088. _this._loadFile(url, function (data) {
  29089. resolve(data);
  29090. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29091. reject(exception);
  29092. });
  29093. });
  29094. };
  29095. // Statics
  29096. Scene._FOGMODE_NONE = 0;
  29097. Scene._FOGMODE_EXP = 1;
  29098. Scene._FOGMODE_EXP2 = 2;
  29099. Scene._FOGMODE_LINEAR = 3;
  29100. Scene._uniqueIdCounter = 0;
  29101. /**
  29102. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29103. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29104. */
  29105. Scene.MinDeltaTime = 1.0;
  29106. /**
  29107. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29108. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29109. */
  29110. Scene.MaxDeltaTime = 1000.0;
  29111. /** The distance in pixel that you have to move to prevent some events */
  29112. Scene.DragMovementThreshold = 10; // in pixels
  29113. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29114. Scene.LongPressDelay = 500; // in milliseconds
  29115. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29116. Scene.DoubleClickDelay = 300; // in milliseconds
  29117. /** If you need to check double click without raising a single click at first click, enable this flag */
  29118. Scene.ExclusiveDoubleClickMode = false;
  29119. return Scene;
  29120. }());
  29121. BABYLON.Scene = Scene;
  29122. })(BABYLON || (BABYLON = {}));
  29123. //# sourceMappingURL=babylon.scene.js.map
  29124. var BABYLON;
  29125. (function (BABYLON) {
  29126. /**
  29127. * Set of assets to keep when moving a scene into an asset container.
  29128. */
  29129. var KeepAssets = /** @class */ (function () {
  29130. function KeepAssets() {
  29131. /**
  29132. * Cameras to keep.
  29133. */
  29134. this.cameras = new Array();
  29135. /**
  29136. * Lights to keep.
  29137. */
  29138. this.lights = new Array();
  29139. /**
  29140. * Meshes to keep.
  29141. */
  29142. this.meshes = new Array();
  29143. /**
  29144. * Skeletons to keep.
  29145. */
  29146. this.skeletons = new Array();
  29147. /**
  29148. * ParticleSystems to keep.
  29149. */
  29150. this.particleSystems = new Array();
  29151. /**
  29152. * Animations to keep.
  29153. */
  29154. this.animations = new Array();
  29155. /**
  29156. * AnimationGroups to keep.
  29157. */
  29158. this.animationGroups = new Array();
  29159. /**
  29160. * MultiMaterials to keep.
  29161. */
  29162. this.multiMaterials = new Array();
  29163. /**
  29164. * Materials to keep.
  29165. */
  29166. this.materials = new Array();
  29167. /**
  29168. * MorphTargetManagers to keep.
  29169. */
  29170. this.morphTargetManagers = new Array();
  29171. /**
  29172. * Geometries to keep.
  29173. */
  29174. this.geometries = new Array();
  29175. /**
  29176. * TransformNodes to keep.
  29177. */
  29178. this.transformNodes = new Array();
  29179. /**
  29180. * LensFlareSystems to keep.
  29181. */
  29182. this.lensFlareSystems = new Array();
  29183. /**
  29184. * ShadowGenerators to keep.
  29185. */
  29186. this.shadowGenerators = new Array();
  29187. /**
  29188. * ActionManagers to keep.
  29189. */
  29190. this.actionManagers = new Array();
  29191. /**
  29192. * Sounds to keep.
  29193. */
  29194. this.sounds = new Array();
  29195. /**
  29196. * Textures to keep.
  29197. */
  29198. this.textures = new Array();
  29199. /**
  29200. * Effect layers to keep.
  29201. */
  29202. this.effectLayers = new Array();
  29203. }
  29204. return KeepAssets;
  29205. }());
  29206. BABYLON.KeepAssets = KeepAssets;
  29207. /**
  29208. * Container with a set of assets that can be added or removed from a scene.
  29209. */
  29210. var AssetContainer = /** @class */ (function () {
  29211. /**
  29212. * Instantiates an AssetContainer.
  29213. * @param scene The scene the AssetContainer belongs to.
  29214. */
  29215. function AssetContainer(scene) {
  29216. // Objects
  29217. /**
  29218. * Cameras populated in the container.
  29219. */
  29220. this.cameras = new Array();
  29221. /**
  29222. * Lights populated in the container.
  29223. */
  29224. this.lights = new Array();
  29225. /**
  29226. * Meshes populated in the container.
  29227. */
  29228. this.meshes = new Array();
  29229. /**
  29230. * Skeletons populated in the container.
  29231. */
  29232. this.skeletons = new Array();
  29233. /**
  29234. * ParticleSystems populated in the container.
  29235. */
  29236. this.particleSystems = new Array();
  29237. /**
  29238. * Animations populated in the container.
  29239. */
  29240. this.animations = new Array();
  29241. /**
  29242. * AnimationGroups populated in the container.
  29243. */
  29244. this.animationGroups = new Array();
  29245. /**
  29246. * MultiMaterials populated in the container.
  29247. */
  29248. this.multiMaterials = new Array();
  29249. /**
  29250. * Materials populated in the container.
  29251. */
  29252. this.materials = new Array();
  29253. /**
  29254. * MorphTargetManagers populated in the container.
  29255. */
  29256. this.morphTargetManagers = new Array();
  29257. /**
  29258. * Geometries populated in the container.
  29259. */
  29260. this.geometries = new Array();
  29261. /**
  29262. * TransformNodes populated in the container.
  29263. */
  29264. this.transformNodes = new Array();
  29265. /**
  29266. * LensFlareSystems populated in the container.
  29267. */
  29268. this.lensFlareSystems = new Array();
  29269. /**
  29270. * ShadowGenerators populated in the container.
  29271. */
  29272. this.shadowGenerators = new Array();
  29273. /**
  29274. * ActionManagers populated in the container.
  29275. */
  29276. this.actionManagers = new Array();
  29277. /**
  29278. * Sounds populated in the container.
  29279. */
  29280. this.sounds = new Array();
  29281. /**
  29282. * Textures populated in the container.
  29283. */
  29284. this.textures = new Array();
  29285. /**
  29286. * Effect layers populated in the container.
  29287. */
  29288. this.effectLayers = new Array();
  29289. this.scene = scene;
  29290. }
  29291. /**
  29292. * Adds all the assets from the container to the scene.
  29293. */
  29294. AssetContainer.prototype.addAllToScene = function () {
  29295. var _this = this;
  29296. this.cameras.forEach(function (o) {
  29297. _this.scene.addCamera(o);
  29298. });
  29299. this.lights.forEach(function (o) {
  29300. _this.scene.addLight(o);
  29301. });
  29302. this.meshes.forEach(function (o) {
  29303. _this.scene.addMesh(o);
  29304. });
  29305. this.skeletons.forEach(function (o) {
  29306. _this.scene.addSkeleton(o);
  29307. });
  29308. this.particleSystems.forEach(function (o) {
  29309. _this.scene.addParticleSystem(o);
  29310. });
  29311. this.animations.forEach(function (o) {
  29312. _this.scene.addAnimation(o);
  29313. });
  29314. this.animationGroups.forEach(function (o) {
  29315. _this.scene.addAnimationGroup(o);
  29316. });
  29317. this.multiMaterials.forEach(function (o) {
  29318. _this.scene.addMultiMaterial(o);
  29319. });
  29320. this.materials.forEach(function (o) {
  29321. _this.scene.addMaterial(o);
  29322. });
  29323. this.morphTargetManagers.forEach(function (o) {
  29324. _this.scene.addMorphTargetManager(o);
  29325. });
  29326. this.geometries.forEach(function (o) {
  29327. _this.scene.addGeometry(o);
  29328. });
  29329. this.transformNodes.forEach(function (o) {
  29330. _this.scene.addTransformNode(o);
  29331. });
  29332. this.lensFlareSystems.forEach(function (o) {
  29333. _this.scene.addLensFlareSystem(o);
  29334. });
  29335. this.actionManagers.forEach(function (o) {
  29336. _this.scene.addActionManager(o);
  29337. });
  29338. this.sounds.forEach(function (o) {
  29339. o.play();
  29340. o.autoplay = true;
  29341. _this.scene.mainSoundTrack.AddSound(o);
  29342. });
  29343. this.textures.forEach(function (o) {
  29344. _this.scene.addTexture(o);
  29345. });
  29346. this.effectLayers.forEach(function (o) {
  29347. _this.scene.addEffectLayer(o);
  29348. });
  29349. };
  29350. /**
  29351. * Removes all the assets in the container from the scene
  29352. */
  29353. AssetContainer.prototype.removeAllFromScene = function () {
  29354. var _this = this;
  29355. this.cameras.forEach(function (o) {
  29356. _this.scene.removeCamera(o);
  29357. });
  29358. this.lights.forEach(function (o) {
  29359. _this.scene.removeLight(o);
  29360. });
  29361. this.meshes.forEach(function (o) {
  29362. _this.scene.removeMesh(o);
  29363. });
  29364. this.skeletons.forEach(function (o) {
  29365. _this.scene.removeSkeleton(o);
  29366. });
  29367. this.particleSystems.forEach(function (o) {
  29368. _this.scene.removeParticleSystem(o);
  29369. });
  29370. this.animations.forEach(function (o) {
  29371. _this.scene.removeAnimation(o);
  29372. });
  29373. this.animationGroups.forEach(function (o) {
  29374. _this.scene.removeAnimationGroup(o);
  29375. });
  29376. this.multiMaterials.forEach(function (o) {
  29377. _this.scene.removeMultiMaterial(o);
  29378. });
  29379. this.materials.forEach(function (o) {
  29380. _this.scene.removeMaterial(o);
  29381. });
  29382. this.morphTargetManagers.forEach(function (o) {
  29383. _this.scene.removeMorphTargetManager(o);
  29384. });
  29385. this.geometries.forEach(function (o) {
  29386. _this.scene.removeGeometry(o);
  29387. });
  29388. this.transformNodes.forEach(function (o) {
  29389. _this.scene.removeTransformNode(o);
  29390. });
  29391. this.lensFlareSystems.forEach(function (o) {
  29392. _this.scene.removeLensFlareSystem(o);
  29393. });
  29394. this.actionManagers.forEach(function (o) {
  29395. _this.scene.removeActionManager(o);
  29396. });
  29397. this.sounds.forEach(function (o) {
  29398. o.stop();
  29399. o.autoplay = false;
  29400. _this.scene.mainSoundTrack.RemoveSound(o);
  29401. });
  29402. this.textures.forEach(function (o) {
  29403. _this.scene.removeTexture(o);
  29404. });
  29405. this.effectLayers.forEach(function (o) {
  29406. _this.scene.removeEffectLayer(o);
  29407. });
  29408. };
  29409. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29410. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29411. var asset = sourceAssets_1[_i];
  29412. var move = true;
  29413. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29414. var keepAsset = keepAssets_1[_a];
  29415. if (asset === keepAsset) {
  29416. move = false;
  29417. break;
  29418. }
  29419. }
  29420. if (move) {
  29421. targetAssets.push(asset);
  29422. }
  29423. }
  29424. };
  29425. /**
  29426. * Removes all the assets contained in the scene and adds them to the container.
  29427. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29428. */
  29429. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29430. if (keepAssets === undefined) {
  29431. keepAssets = new KeepAssets();
  29432. }
  29433. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29434. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29435. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29436. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29437. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29438. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29439. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29440. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29441. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29442. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29443. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29444. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29445. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29446. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29447. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29448. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29449. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29450. this.removeAllFromScene();
  29451. };
  29452. /**
  29453. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29454. * @returns the root mesh
  29455. */
  29456. AssetContainer.prototype.createRootMesh = function () {
  29457. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29458. this.meshes.forEach(function (m) {
  29459. if (!m.parent) {
  29460. rootMesh.addChild(m);
  29461. }
  29462. });
  29463. this.meshes.unshift(rootMesh);
  29464. return rootMesh;
  29465. };
  29466. return AssetContainer;
  29467. }());
  29468. BABYLON.AssetContainer = AssetContainer;
  29469. })(BABYLON || (BABYLON = {}));
  29470. //# sourceMappingURL=babylon.assetContainer.js.map
  29471. var BABYLON;
  29472. (function (BABYLON) {
  29473. var Buffer = /** @class */ (function () {
  29474. /**
  29475. * Constructor
  29476. * @param engine the engine
  29477. * @param data the data to use for this buffer
  29478. * @param updatable whether the data is updatable
  29479. * @param stride the stride (optional)
  29480. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29481. * @param instanced whether the buffer is instanced (optional)
  29482. * @param useBytes set to true if the stride in in bytes (optional)
  29483. */
  29484. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29485. if (stride === void 0) { stride = 0; }
  29486. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29487. if (instanced === void 0) { instanced = false; }
  29488. if (useBytes === void 0) { useBytes = false; }
  29489. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29490. this._engine = engine.getScene().getEngine();
  29491. }
  29492. else {
  29493. this._engine = engine;
  29494. }
  29495. this._updatable = updatable;
  29496. this._instanced = instanced;
  29497. this._data = data;
  29498. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29499. if (!postponeInternalCreation) { // by default
  29500. this.create();
  29501. }
  29502. }
  29503. /**
  29504. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29505. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29506. * @param offset defines offset in the buffer (0 by default)
  29507. * @param size defines the size in floats of attributes (position is 3 for instance)
  29508. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29509. * @param instanced defines if the vertex buffer contains indexed data
  29510. * @param useBytes defines if the offset and stride are in bytes
  29511. * @returns the new vertex buffer
  29512. */
  29513. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29514. if (useBytes === void 0) { useBytes = false; }
  29515. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29516. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29517. // a lot of these parameters are ignored as they are overriden by the buffer
  29518. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29519. };
  29520. // Properties
  29521. Buffer.prototype.isUpdatable = function () {
  29522. return this._updatable;
  29523. };
  29524. Buffer.prototype.getData = function () {
  29525. return this._data;
  29526. };
  29527. Buffer.prototype.getBuffer = function () {
  29528. return this._buffer;
  29529. };
  29530. /**
  29531. * Gets the stride in float32 units (i.e. byte stride / 4).
  29532. * May not be an integer if the byte stride is not divisible by 4.
  29533. * DEPRECATED. Use byteStride instead.
  29534. * @returns the stride in float32 units
  29535. */
  29536. Buffer.prototype.getStrideSize = function () {
  29537. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29538. };
  29539. // Methods
  29540. Buffer.prototype.create = function (data) {
  29541. if (data === void 0) { data = null; }
  29542. if (!data && this._buffer) {
  29543. return; // nothing to do
  29544. }
  29545. data = data || this._data;
  29546. if (!data) {
  29547. return;
  29548. }
  29549. if (!this._buffer) { // create buffer
  29550. if (this._updatable) {
  29551. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29552. this._data = data;
  29553. }
  29554. else {
  29555. this._buffer = this._engine.createVertexBuffer(data);
  29556. }
  29557. }
  29558. else if (this._updatable) { // update buffer
  29559. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29560. this._data = data;
  29561. }
  29562. };
  29563. Buffer.prototype._rebuild = function () {
  29564. this._buffer = null;
  29565. this.create(this._data);
  29566. };
  29567. Buffer.prototype.update = function (data) {
  29568. this.create(data);
  29569. };
  29570. /**
  29571. * Updates the data directly.
  29572. * @param data the new data
  29573. * @param offset the new offset
  29574. * @param vertexCount the vertex count (optional)
  29575. * @param useBytes set to true if the offset is in bytes
  29576. */
  29577. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29578. if (useBytes === void 0) { useBytes = false; }
  29579. if (!this._buffer) {
  29580. return;
  29581. }
  29582. if (this._updatable) { // update buffer
  29583. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29584. this._data = null;
  29585. }
  29586. };
  29587. Buffer.prototype.dispose = function () {
  29588. if (!this._buffer) {
  29589. return;
  29590. }
  29591. if (this._engine._releaseBuffer(this._buffer)) {
  29592. this._buffer = null;
  29593. }
  29594. };
  29595. return Buffer;
  29596. }());
  29597. BABYLON.Buffer = Buffer;
  29598. })(BABYLON || (BABYLON = {}));
  29599. //# sourceMappingURL=babylon.buffer.js.map
  29600. var BABYLON;
  29601. (function (BABYLON) {
  29602. var VertexBuffer = /** @class */ (function () {
  29603. /**
  29604. * Constructor
  29605. * @param engine the engine
  29606. * @param data the data to use for this vertex buffer
  29607. * @param kind the vertex buffer kind
  29608. * @param updatable whether the data is updatable
  29609. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29610. * @param stride the stride (optional)
  29611. * @param instanced whether the buffer is instanced (optional)
  29612. * @param offset the offset of the data (optional)
  29613. * @param size the number of components (optional)
  29614. * @param type the type of the component (optional)
  29615. * @param normalized whether the data contains normalized data (optional)
  29616. * @param useBytes set to true if stride and offset are in bytes (optional)
  29617. */
  29618. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29619. if (normalized === void 0) { normalized = false; }
  29620. if (useBytes === void 0) { useBytes = false; }
  29621. if (data instanceof BABYLON.Buffer) {
  29622. this._buffer = data;
  29623. this._ownsBuffer = false;
  29624. }
  29625. else {
  29626. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29627. this._ownsBuffer = true;
  29628. }
  29629. this._kind = kind;
  29630. if (type == undefined) {
  29631. var data_1 = this.getData();
  29632. this.type = VertexBuffer.FLOAT;
  29633. if (data_1 instanceof Int8Array)
  29634. this.type = VertexBuffer.BYTE;
  29635. else if (data_1 instanceof Uint8Array)
  29636. this.type = VertexBuffer.UNSIGNED_BYTE;
  29637. else if (data_1 instanceof Int16Array)
  29638. this.type = VertexBuffer.SHORT;
  29639. else if (data_1 instanceof Uint16Array)
  29640. this.type = VertexBuffer.UNSIGNED_SHORT;
  29641. else if (data_1 instanceof Int32Array)
  29642. this.type = VertexBuffer.INT;
  29643. else if (data_1 instanceof Uint32Array)
  29644. this.type = VertexBuffer.UNSIGNED_INT;
  29645. }
  29646. else {
  29647. this.type = type;
  29648. }
  29649. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29650. if (useBytes) {
  29651. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29652. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29653. this.byteOffset = offset || 0;
  29654. }
  29655. else {
  29656. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29657. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29658. this.byteOffset = (offset || 0) * typeByteLength;
  29659. }
  29660. this.normalized = normalized;
  29661. this._instanced = instanced !== undefined ? instanced : false;
  29662. this._instanceDivisor = instanced ? 1 : 0;
  29663. }
  29664. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29665. /**
  29666. * Gets or sets the instance divisor when in instanced mode
  29667. */
  29668. get: function () {
  29669. return this._instanceDivisor;
  29670. },
  29671. set: function (value) {
  29672. this._instanceDivisor = value;
  29673. if (value == 0) {
  29674. this._instanced = false;
  29675. }
  29676. else {
  29677. this._instanced = true;
  29678. }
  29679. },
  29680. enumerable: true,
  29681. configurable: true
  29682. });
  29683. VertexBuffer.prototype._rebuild = function () {
  29684. if (!this._buffer) {
  29685. return;
  29686. }
  29687. this._buffer._rebuild();
  29688. };
  29689. /**
  29690. * Returns the kind of the VertexBuffer (string).
  29691. */
  29692. VertexBuffer.prototype.getKind = function () {
  29693. return this._kind;
  29694. };
  29695. // Properties
  29696. /**
  29697. * Boolean : is the VertexBuffer updatable ?
  29698. */
  29699. VertexBuffer.prototype.isUpdatable = function () {
  29700. return this._buffer.isUpdatable();
  29701. };
  29702. /**
  29703. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29704. */
  29705. VertexBuffer.prototype.getData = function () {
  29706. return this._buffer.getData();
  29707. };
  29708. /**
  29709. * Returns the WebGLBuffer associated to the VertexBuffer.
  29710. */
  29711. VertexBuffer.prototype.getBuffer = function () {
  29712. return this._buffer.getBuffer();
  29713. };
  29714. /**
  29715. * Returns the stride as a multiple of the type byte length.
  29716. * DEPRECATED. Use byteStride instead.
  29717. */
  29718. VertexBuffer.prototype.getStrideSize = function () {
  29719. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29720. };
  29721. /**
  29722. * Returns the offset as a multiple of the type byte length.
  29723. * DEPRECATED. Use byteOffset instead.
  29724. */
  29725. VertexBuffer.prototype.getOffset = function () {
  29726. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29727. };
  29728. /**
  29729. * Returns the number of components per vertex attribute (integer).
  29730. */
  29731. VertexBuffer.prototype.getSize = function () {
  29732. return this._size;
  29733. };
  29734. /**
  29735. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29736. */
  29737. VertexBuffer.prototype.getIsInstanced = function () {
  29738. return this._instanced;
  29739. };
  29740. /**
  29741. * Returns the instancing divisor, zero for non-instanced (integer).
  29742. */
  29743. VertexBuffer.prototype.getInstanceDivisor = function () {
  29744. return this._instanceDivisor;
  29745. };
  29746. // Methods
  29747. /**
  29748. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29749. * Returns the created WebGLBuffer.
  29750. */
  29751. VertexBuffer.prototype.create = function (data) {
  29752. return this._buffer.create(data);
  29753. };
  29754. /**
  29755. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29756. * This function will create a new buffer if the current one is not updatable
  29757. * Returns the updated WebGLBuffer.
  29758. */
  29759. VertexBuffer.prototype.update = function (data) {
  29760. return this._buffer.update(data);
  29761. };
  29762. /**
  29763. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29764. * Returns the directly updated WebGLBuffer.
  29765. * @param data the new data
  29766. * @param offset the new offset
  29767. * @param useBytes set to true if the offset is in bytes
  29768. */
  29769. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29770. if (useBytes === void 0) { useBytes = false; }
  29771. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29772. };
  29773. /**
  29774. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29775. */
  29776. VertexBuffer.prototype.dispose = function () {
  29777. if (this._ownsBuffer) {
  29778. this._buffer.dispose();
  29779. }
  29780. };
  29781. /**
  29782. * Enumerates each value of this vertex buffer as numbers.
  29783. * @param count the number of values to enumerate
  29784. * @param callback the callback function called for each value
  29785. */
  29786. VertexBuffer.prototype.forEach = function (count, callback) {
  29787. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29788. };
  29789. Object.defineProperty(VertexBuffer, "PositionKind", {
  29790. get: function () {
  29791. return VertexBuffer._PositionKind;
  29792. },
  29793. enumerable: true,
  29794. configurable: true
  29795. });
  29796. Object.defineProperty(VertexBuffer, "NormalKind", {
  29797. get: function () {
  29798. return VertexBuffer._NormalKind;
  29799. },
  29800. enumerable: true,
  29801. configurable: true
  29802. });
  29803. Object.defineProperty(VertexBuffer, "TangentKind", {
  29804. get: function () {
  29805. return VertexBuffer._TangentKind;
  29806. },
  29807. enumerable: true,
  29808. configurable: true
  29809. });
  29810. Object.defineProperty(VertexBuffer, "UVKind", {
  29811. get: function () {
  29812. return VertexBuffer._UVKind;
  29813. },
  29814. enumerable: true,
  29815. configurable: true
  29816. });
  29817. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29818. get: function () {
  29819. return VertexBuffer._UV2Kind;
  29820. },
  29821. enumerable: true,
  29822. configurable: true
  29823. });
  29824. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29825. get: function () {
  29826. return VertexBuffer._UV3Kind;
  29827. },
  29828. enumerable: true,
  29829. configurable: true
  29830. });
  29831. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29832. get: function () {
  29833. return VertexBuffer._UV4Kind;
  29834. },
  29835. enumerable: true,
  29836. configurable: true
  29837. });
  29838. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29839. get: function () {
  29840. return VertexBuffer._UV5Kind;
  29841. },
  29842. enumerable: true,
  29843. configurable: true
  29844. });
  29845. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29846. get: function () {
  29847. return VertexBuffer._UV6Kind;
  29848. },
  29849. enumerable: true,
  29850. configurable: true
  29851. });
  29852. Object.defineProperty(VertexBuffer, "ColorKind", {
  29853. get: function () {
  29854. return VertexBuffer._ColorKind;
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29860. get: function () {
  29861. return VertexBuffer._MatricesIndicesKind;
  29862. },
  29863. enumerable: true,
  29864. configurable: true
  29865. });
  29866. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29867. get: function () {
  29868. return VertexBuffer._MatricesWeightsKind;
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29874. get: function () {
  29875. return VertexBuffer._MatricesIndicesExtraKind;
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29881. get: function () {
  29882. return VertexBuffer._MatricesWeightsExtraKind;
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. /**
  29888. * Deduces the stride given a kind.
  29889. * @param kind The kind string to deduce
  29890. * @returns The deduced stride
  29891. */
  29892. VertexBuffer.DeduceStride = function (kind) {
  29893. switch (kind) {
  29894. case VertexBuffer.UVKind:
  29895. case VertexBuffer.UV2Kind:
  29896. case VertexBuffer.UV3Kind:
  29897. case VertexBuffer.UV4Kind:
  29898. case VertexBuffer.UV5Kind:
  29899. case VertexBuffer.UV6Kind:
  29900. return 2;
  29901. case VertexBuffer.NormalKind:
  29902. case VertexBuffer.PositionKind:
  29903. return 3;
  29904. case VertexBuffer.ColorKind:
  29905. case VertexBuffer.MatricesIndicesKind:
  29906. case VertexBuffer.MatricesIndicesExtraKind:
  29907. case VertexBuffer.MatricesWeightsKind:
  29908. case VertexBuffer.MatricesWeightsExtraKind:
  29909. case VertexBuffer.TangentKind:
  29910. return 4;
  29911. default:
  29912. throw new Error("Invalid kind '" + kind + "'");
  29913. }
  29914. };
  29915. /**
  29916. * Gets the byte length of the given type.
  29917. * @param type the type
  29918. * @returns the number of bytes
  29919. */
  29920. VertexBuffer.GetTypeByteLength = function (type) {
  29921. switch (type) {
  29922. case VertexBuffer.BYTE:
  29923. case VertexBuffer.UNSIGNED_BYTE:
  29924. return 1;
  29925. case VertexBuffer.SHORT:
  29926. case VertexBuffer.UNSIGNED_SHORT:
  29927. return 2;
  29928. case VertexBuffer.INT:
  29929. case VertexBuffer.FLOAT:
  29930. return 4;
  29931. default:
  29932. throw new Error("Invalid type '" + type + "'");
  29933. }
  29934. };
  29935. /**
  29936. * Enumerates each value of the given parameters as numbers.
  29937. * @param data the data to enumerate
  29938. * @param byteOffset the byte offset of the data
  29939. * @param byteStride the byte stride of the data
  29940. * @param componentCount the number of components per element
  29941. * @param componentType the type of the component
  29942. * @param count the total number of components
  29943. * @param normalized whether the data is normalized
  29944. * @param callback the callback function called for each value
  29945. */
  29946. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29947. if (data instanceof Array) {
  29948. var offset = byteOffset / 4;
  29949. var stride = byteStride / 4;
  29950. for (var index = 0; index < count; index += componentCount) {
  29951. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29952. callback(data[offset + componentIndex], index + componentIndex);
  29953. }
  29954. offset += stride;
  29955. }
  29956. }
  29957. else {
  29958. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29959. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29960. for (var index = 0; index < count; index += componentCount) {
  29961. var componentByteOffset = byteOffset;
  29962. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29963. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29964. callback(value, index + componentIndex);
  29965. componentByteOffset += componentByteLength;
  29966. }
  29967. byteOffset += byteStride;
  29968. }
  29969. }
  29970. };
  29971. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29972. switch (type) {
  29973. case VertexBuffer.BYTE: {
  29974. var value = dataView.getInt8(byteOffset);
  29975. if (normalized) {
  29976. value = Math.max(value / 127, -1);
  29977. }
  29978. return value;
  29979. }
  29980. case VertexBuffer.UNSIGNED_BYTE: {
  29981. var value = dataView.getUint8(byteOffset);
  29982. if (normalized) {
  29983. value = value / 255;
  29984. }
  29985. return value;
  29986. }
  29987. case VertexBuffer.SHORT: {
  29988. var value = dataView.getInt16(byteOffset, true);
  29989. if (normalized) {
  29990. value = Math.max(value / 16383, -1);
  29991. }
  29992. return value;
  29993. }
  29994. case VertexBuffer.UNSIGNED_SHORT: {
  29995. var value = dataView.getUint16(byteOffset, true);
  29996. if (normalized) {
  29997. value = value / 65535;
  29998. }
  29999. return value;
  30000. }
  30001. case VertexBuffer.FLOAT: {
  30002. return dataView.getFloat32(byteOffset, true);
  30003. }
  30004. default: {
  30005. throw new Error("Invalid component type " + type);
  30006. }
  30007. }
  30008. };
  30009. /**
  30010. * The byte type.
  30011. */
  30012. VertexBuffer.BYTE = 5120;
  30013. /**
  30014. * The unsigned byte type.
  30015. */
  30016. VertexBuffer.UNSIGNED_BYTE = 5121;
  30017. /**
  30018. * The short type.
  30019. */
  30020. VertexBuffer.SHORT = 5122;
  30021. /**
  30022. * The unsigned short type.
  30023. */
  30024. VertexBuffer.UNSIGNED_SHORT = 5123;
  30025. /**
  30026. * The integer type.
  30027. */
  30028. VertexBuffer.INT = 5124;
  30029. /**
  30030. * The unsigned integer type.
  30031. */
  30032. VertexBuffer.UNSIGNED_INT = 5125;
  30033. /**
  30034. * The float type.
  30035. */
  30036. VertexBuffer.FLOAT = 5126;
  30037. // Enums
  30038. VertexBuffer._PositionKind = "position";
  30039. VertexBuffer._NormalKind = "normal";
  30040. VertexBuffer._TangentKind = "tangent";
  30041. VertexBuffer._UVKind = "uv";
  30042. VertexBuffer._UV2Kind = "uv2";
  30043. VertexBuffer._UV3Kind = "uv3";
  30044. VertexBuffer._UV4Kind = "uv4";
  30045. VertexBuffer._UV5Kind = "uv5";
  30046. VertexBuffer._UV6Kind = "uv6";
  30047. VertexBuffer._ColorKind = "color";
  30048. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30049. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30050. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30051. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30052. return VertexBuffer;
  30053. }());
  30054. BABYLON.VertexBuffer = VertexBuffer;
  30055. })(BABYLON || (BABYLON = {}));
  30056. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30057. var BABYLON;
  30058. (function (BABYLON) {
  30059. /**
  30060. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30061. */
  30062. var DummyInternalTextureTracker = /** @class */ (function () {
  30063. function DummyInternalTextureTracker() {
  30064. /**
  30065. * Gets or set the previous tracker in the list
  30066. */
  30067. this.previous = null;
  30068. /**
  30069. * Gets or set the next tracker in the list
  30070. */
  30071. this.next = null;
  30072. }
  30073. return DummyInternalTextureTracker;
  30074. }());
  30075. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30076. })(BABYLON || (BABYLON = {}));
  30077. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30078. var BABYLON;
  30079. (function (BABYLON) {
  30080. /**
  30081. * Class used to store data associated with WebGL texture data for the engine
  30082. * This class should not be used directly
  30083. */
  30084. var InternalTexture = /** @class */ (function () {
  30085. /**
  30086. * Creates a new InternalTexture
  30087. * @param engine defines the engine to use
  30088. * @param dataSource defines the type of data that will be used
  30089. */
  30090. function InternalTexture(engine, dataSource) {
  30091. /**
  30092. * Observable called when the texture is loaded
  30093. */
  30094. this.onLoadedObservable = new BABYLON.Observable();
  30095. /**
  30096. * Gets or set the previous tracker in the list
  30097. */
  30098. this.previous = null;
  30099. /**
  30100. * Gets or set the next tracker in the list
  30101. */
  30102. this.next = null;
  30103. // Private
  30104. /** @hidden */
  30105. this._initialSlot = -1;
  30106. /** @hidden */
  30107. this._designatedSlot = -1;
  30108. /** @hidden */
  30109. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30110. /** @hidden */
  30111. this._comparisonFunction = 0;
  30112. /** @hidden */
  30113. this._isRGBD = false;
  30114. /** @hidden */
  30115. this._references = 1;
  30116. this._engine = engine;
  30117. this._dataSource = dataSource;
  30118. this._webGLTexture = engine._createTexture();
  30119. }
  30120. /**
  30121. * Gets the Engine the texture belongs to.
  30122. * @returns The babylon engine
  30123. */
  30124. InternalTexture.prototype.getEngine = function () {
  30125. return this._engine;
  30126. };
  30127. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30128. /**
  30129. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30130. */
  30131. get: function () {
  30132. return this._dataSource;
  30133. },
  30134. enumerable: true,
  30135. configurable: true
  30136. });
  30137. /**
  30138. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30139. */
  30140. InternalTexture.prototype.incrementReferences = function () {
  30141. this._references++;
  30142. };
  30143. /**
  30144. * Change the size of the texture (not the size of the content)
  30145. * @param width defines the new width
  30146. * @param height defines the new height
  30147. * @param depth defines the new depth (1 by default)
  30148. */
  30149. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30150. if (depth === void 0) { depth = 1; }
  30151. this.width = width;
  30152. this.height = height;
  30153. this.depth = depth;
  30154. this.baseWidth = width;
  30155. this.baseHeight = height;
  30156. this.baseDepth = depth;
  30157. this._size = width * height * depth;
  30158. };
  30159. /** @hidden */
  30160. InternalTexture.prototype._rebuild = function () {
  30161. var _this = this;
  30162. var proxy;
  30163. this.isReady = false;
  30164. this._cachedCoordinatesMode = null;
  30165. this._cachedWrapU = null;
  30166. this._cachedWrapV = null;
  30167. this._cachedAnisotropicFilteringLevel = null;
  30168. switch (this._dataSource) {
  30169. case InternalTexture.DATASOURCE_TEMP:
  30170. return;
  30171. case InternalTexture.DATASOURCE_URL:
  30172. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30173. _this.isReady = true;
  30174. }, null, this._buffer, undefined, this.format);
  30175. proxy._swapAndDie(this);
  30176. return;
  30177. case InternalTexture.DATASOURCE_RAW:
  30178. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30179. proxy._swapAndDie(this);
  30180. this.isReady = true;
  30181. return;
  30182. case InternalTexture.DATASOURCE_RAW3D:
  30183. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30184. proxy._swapAndDie(this);
  30185. this.isReady = true;
  30186. return;
  30187. case InternalTexture.DATASOURCE_DYNAMIC:
  30188. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30189. proxy._swapAndDie(this);
  30190. // The engine will make sure to update content so no need to flag it as isReady = true
  30191. return;
  30192. case InternalTexture.DATASOURCE_RENDERTARGET:
  30193. var options = new BABYLON.RenderTargetCreationOptions();
  30194. options.generateDepthBuffer = this._generateDepthBuffer;
  30195. options.generateMipMaps = this.generateMipMaps;
  30196. options.generateStencilBuffer = this._generateStencilBuffer;
  30197. options.samplingMode = this.samplingMode;
  30198. options.type = this.type;
  30199. if (this.isCube) {
  30200. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30201. }
  30202. else {
  30203. var size = {
  30204. width: this.width,
  30205. height: this.height
  30206. };
  30207. proxy = this._engine.createRenderTargetTexture(size, options);
  30208. }
  30209. proxy._swapAndDie(this);
  30210. this.isReady = true;
  30211. return;
  30212. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30213. var depthTextureOptions = {
  30214. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30215. comparisonFunction: this._comparisonFunction,
  30216. generateStencil: this._generateStencilBuffer,
  30217. isCube: this.isCube
  30218. };
  30219. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30220. proxy._swapAndDie(this);
  30221. this.isReady = true;
  30222. return;
  30223. case InternalTexture.DATASOURCE_CUBE:
  30224. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30225. _this.isReady = true;
  30226. }, null, this.format, this._extension);
  30227. proxy._swapAndDie(this);
  30228. return;
  30229. case InternalTexture.DATASOURCE_CUBERAW:
  30230. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30231. proxy._swapAndDie(this);
  30232. this.isReady = true;
  30233. return;
  30234. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30235. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30236. if (proxy) {
  30237. proxy._swapAndDie(_this);
  30238. }
  30239. _this.isReady = true;
  30240. }, null, this.format, this._extension);
  30241. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30242. return;
  30243. }
  30244. };
  30245. InternalTexture.prototype._swapAndDie = function (target) {
  30246. target._webGLTexture = this._webGLTexture;
  30247. if (this._framebuffer) {
  30248. target._framebuffer = this._framebuffer;
  30249. }
  30250. if (this._depthStencilBuffer) {
  30251. target._depthStencilBuffer = this._depthStencilBuffer;
  30252. }
  30253. if (this._lodTextureHigh) {
  30254. if (target._lodTextureHigh) {
  30255. target._lodTextureHigh.dispose();
  30256. }
  30257. target._lodTextureHigh = this._lodTextureHigh;
  30258. }
  30259. if (this._lodTextureMid) {
  30260. if (target._lodTextureMid) {
  30261. target._lodTextureMid.dispose();
  30262. }
  30263. target._lodTextureMid = this._lodTextureMid;
  30264. }
  30265. if (this._lodTextureLow) {
  30266. if (target._lodTextureLow) {
  30267. target._lodTextureLow.dispose();
  30268. }
  30269. target._lodTextureLow = this._lodTextureLow;
  30270. }
  30271. var cache = this._engine.getLoadedTexturesCache();
  30272. var index = cache.indexOf(this);
  30273. if (index !== -1) {
  30274. cache.splice(index, 1);
  30275. }
  30276. };
  30277. /**
  30278. * Dispose the current allocated resources
  30279. */
  30280. InternalTexture.prototype.dispose = function () {
  30281. if (!this._webGLTexture) {
  30282. return;
  30283. }
  30284. this._references--;
  30285. if (this._references === 0) {
  30286. this._engine._releaseTexture(this);
  30287. this._webGLTexture = null;
  30288. this.previous = null;
  30289. this.next = null;
  30290. }
  30291. };
  30292. /**
  30293. * The source of the texture data is unknown
  30294. */
  30295. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30296. /**
  30297. * Texture data comes from an URL
  30298. */
  30299. InternalTexture.DATASOURCE_URL = 1;
  30300. /**
  30301. * Texture data is only used for temporary storage
  30302. */
  30303. InternalTexture.DATASOURCE_TEMP = 2;
  30304. /**
  30305. * Texture data comes from raw data (ArrayBuffer)
  30306. */
  30307. InternalTexture.DATASOURCE_RAW = 3;
  30308. /**
  30309. * Texture content is dynamic (video or dynamic texture)
  30310. */
  30311. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30312. /**
  30313. * Texture content is generated by rendering to it
  30314. */
  30315. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30316. /**
  30317. * Texture content is part of a multi render target process
  30318. */
  30319. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30320. /**
  30321. * Texture data comes from a cube data file
  30322. */
  30323. InternalTexture.DATASOURCE_CUBE = 7;
  30324. /**
  30325. * Texture data comes from a raw cube data
  30326. */
  30327. InternalTexture.DATASOURCE_CUBERAW = 8;
  30328. /**
  30329. * Texture data come from a prefiltered cube data file
  30330. */
  30331. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30332. /**
  30333. * Texture content is raw 3D data
  30334. */
  30335. InternalTexture.DATASOURCE_RAW3D = 10;
  30336. /**
  30337. * Texture content is a depth texture
  30338. */
  30339. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30340. return InternalTexture;
  30341. }());
  30342. BABYLON.InternalTexture = InternalTexture;
  30343. })(BABYLON || (BABYLON = {}));
  30344. //# sourceMappingURL=babylon.internalTexture.js.map
  30345. var BABYLON;
  30346. (function (BABYLON) {
  30347. var BaseTexture = /** @class */ (function () {
  30348. function BaseTexture(scene) {
  30349. this._hasAlpha = false;
  30350. this.getAlphaFromRGB = false;
  30351. this.level = 1;
  30352. this.coordinatesIndex = 0;
  30353. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30354. /**
  30355. * | Value | Type | Description |
  30356. * | ----- | ------------------ | ----------- |
  30357. * | 0 | CLAMP_ADDRESSMODE | |
  30358. * | 1 | WRAP_ADDRESSMODE | |
  30359. * | 2 | MIRROR_ADDRESSMODE | |
  30360. */
  30361. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30362. /**
  30363. * | Value | Type | Description |
  30364. * | ----- | ------------------ | ----------- |
  30365. * | 0 | CLAMP_ADDRESSMODE | |
  30366. * | 1 | WRAP_ADDRESSMODE | |
  30367. * | 2 | MIRROR_ADDRESSMODE | |
  30368. */
  30369. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30370. /**
  30371. * | Value | Type | Description |
  30372. * | ----- | ------------------ | ----------- |
  30373. * | 0 | CLAMP_ADDRESSMODE | |
  30374. * | 1 | WRAP_ADDRESSMODE | |
  30375. * | 2 | MIRROR_ADDRESSMODE | |
  30376. */
  30377. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30378. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30379. this.isCube = false;
  30380. this.is3D = false;
  30381. this.gammaSpace = true;
  30382. this.invertZ = false;
  30383. this.lodLevelInAlpha = false;
  30384. this.isRenderTarget = false;
  30385. this.animations = new Array();
  30386. /**
  30387. * An event triggered when the texture is disposed.
  30388. */
  30389. this.onDisposeObservable = new BABYLON.Observable();
  30390. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30391. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30392. if (this._scene) {
  30393. this._scene.textures.push(this);
  30394. }
  30395. this._uid = null;
  30396. }
  30397. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30398. get: function () {
  30399. return this._hasAlpha;
  30400. },
  30401. set: function (value) {
  30402. if (this._hasAlpha === value) {
  30403. return;
  30404. }
  30405. this._hasAlpha = value;
  30406. if (this._scene) {
  30407. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30408. }
  30409. },
  30410. enumerable: true,
  30411. configurable: true
  30412. });
  30413. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30414. get: function () {
  30415. return this._coordinatesMode;
  30416. },
  30417. /**
  30418. * How a texture is mapped.
  30419. *
  30420. * | Value | Type | Description |
  30421. * | ----- | ----------------------------------- | ----------- |
  30422. * | 0 | EXPLICIT_MODE | |
  30423. * | 1 | SPHERICAL_MODE | |
  30424. * | 2 | PLANAR_MODE | |
  30425. * | 3 | CUBIC_MODE | |
  30426. * | 4 | PROJECTION_MODE | |
  30427. * | 5 | SKYBOX_MODE | |
  30428. * | 6 | INVCUBIC_MODE | |
  30429. * | 7 | EQUIRECTANGULAR_MODE | |
  30430. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30431. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30432. */
  30433. set: function (value) {
  30434. if (this._coordinatesMode === value) {
  30435. return;
  30436. }
  30437. this._coordinatesMode = value;
  30438. if (this._scene) {
  30439. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30440. }
  30441. },
  30442. enumerable: true,
  30443. configurable: true
  30444. });
  30445. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30446. /**
  30447. * Gets whether or not the texture contains RGBD data.
  30448. */
  30449. get: function () {
  30450. return this._texture != null && this._texture._isRGBD;
  30451. },
  30452. enumerable: true,
  30453. configurable: true
  30454. });
  30455. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30456. get: function () {
  30457. if (this._texture)
  30458. return this._texture._lodGenerationOffset;
  30459. return 0.0;
  30460. },
  30461. set: function (value) {
  30462. if (this._texture)
  30463. this._texture._lodGenerationOffset = value;
  30464. },
  30465. enumerable: true,
  30466. configurable: true
  30467. });
  30468. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30469. get: function () {
  30470. if (this._texture)
  30471. return this._texture._lodGenerationScale;
  30472. return 0.0;
  30473. },
  30474. set: function (value) {
  30475. if (this._texture)
  30476. this._texture._lodGenerationScale = value;
  30477. },
  30478. enumerable: true,
  30479. configurable: true
  30480. });
  30481. Object.defineProperty(BaseTexture.prototype, "uid", {
  30482. get: function () {
  30483. if (!this._uid) {
  30484. this._uid = BABYLON.Tools.RandomId();
  30485. }
  30486. return this._uid;
  30487. },
  30488. enumerable: true,
  30489. configurable: true
  30490. });
  30491. BaseTexture.prototype.toString = function () {
  30492. return this.name;
  30493. };
  30494. BaseTexture.prototype.getClassName = function () {
  30495. return "BaseTexture";
  30496. };
  30497. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30498. set: function (callback) {
  30499. if (this._onDisposeObserver) {
  30500. this.onDisposeObservable.remove(this._onDisposeObserver);
  30501. }
  30502. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30508. get: function () {
  30509. return true;
  30510. },
  30511. enumerable: true,
  30512. configurable: true
  30513. });
  30514. BaseTexture.prototype.getScene = function () {
  30515. return this._scene;
  30516. };
  30517. BaseTexture.prototype.getTextureMatrix = function () {
  30518. return BABYLON.Matrix.IdentityReadOnly;
  30519. };
  30520. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30521. return BABYLON.Matrix.IdentityReadOnly;
  30522. };
  30523. BaseTexture.prototype.getInternalTexture = function () {
  30524. return this._texture;
  30525. };
  30526. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30527. return !this.isBlocking || this.isReady();
  30528. };
  30529. BaseTexture.prototype.isReady = function () {
  30530. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30531. this.delayLoad();
  30532. return false;
  30533. }
  30534. if (this._texture) {
  30535. return this._texture.isReady;
  30536. }
  30537. return false;
  30538. };
  30539. BaseTexture.prototype.getSize = function () {
  30540. if (this._texture && this._texture.width) {
  30541. return new BABYLON.Size(this._texture.width, this._texture.height);
  30542. }
  30543. if (this._texture && this._texture._size) {
  30544. return new BABYLON.Size(this._texture._size, this._texture._size);
  30545. }
  30546. return BABYLON.Size.Zero();
  30547. };
  30548. BaseTexture.prototype.getBaseSize = function () {
  30549. if (!this.isReady() || !this._texture)
  30550. return BABYLON.Size.Zero();
  30551. if (this._texture._size) {
  30552. return new BABYLON.Size(this._texture._size, this._texture._size);
  30553. }
  30554. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30555. };
  30556. BaseTexture.prototype.scale = function (ratio) {
  30557. };
  30558. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30559. get: function () {
  30560. return false;
  30561. },
  30562. enumerable: true,
  30563. configurable: true
  30564. });
  30565. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30566. if (!this._scene) {
  30567. return null;
  30568. }
  30569. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30570. for (var index = 0; index < texturesCache.length; index++) {
  30571. var texturesCacheEntry = texturesCache[index];
  30572. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30573. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30574. texturesCacheEntry.incrementReferences();
  30575. return texturesCacheEntry;
  30576. }
  30577. }
  30578. }
  30579. return null;
  30580. };
  30581. BaseTexture.prototype._rebuild = function () {
  30582. };
  30583. BaseTexture.prototype.delayLoad = function () {
  30584. };
  30585. BaseTexture.prototype.clone = function () {
  30586. return null;
  30587. };
  30588. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30589. get: function () {
  30590. if (!this._texture) {
  30591. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30592. }
  30593. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30594. },
  30595. enumerable: true,
  30596. configurable: true
  30597. });
  30598. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30599. get: function () {
  30600. if (!this._texture) {
  30601. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30602. }
  30603. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30604. },
  30605. enumerable: true,
  30606. configurable: true
  30607. });
  30608. /**
  30609. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30610. * This will returns an RGBA array buffer containing either in values (0-255) or
  30611. * float values (0-1) depending of the underlying buffer type.
  30612. * @param faceIndex The face of the texture to read (in case of cube texture)
  30613. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30614. * @returns The Array buffer containing the pixels data.
  30615. */
  30616. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30617. if (faceIndex === void 0) { faceIndex = 0; }
  30618. if (level === void 0) { level = 0; }
  30619. if (!this._texture) {
  30620. return null;
  30621. }
  30622. var size = this.getSize();
  30623. var width = size.width;
  30624. var height = size.height;
  30625. var scene = this.getScene();
  30626. if (!scene) {
  30627. return null;
  30628. }
  30629. var engine = scene.getEngine();
  30630. if (level != 0) {
  30631. width = width / Math.pow(2, level);
  30632. height = height / Math.pow(2, level);
  30633. width = Math.round(width);
  30634. height = Math.round(height);
  30635. }
  30636. if (this._texture.isCube) {
  30637. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30638. }
  30639. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30640. };
  30641. BaseTexture.prototype.releaseInternalTexture = function () {
  30642. if (this._texture) {
  30643. this._texture.dispose();
  30644. this._texture = null;
  30645. }
  30646. };
  30647. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30648. get: function () {
  30649. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30650. return null;
  30651. }
  30652. if (!this._texture._sphericalPolynomial) {
  30653. this._texture._sphericalPolynomial =
  30654. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30655. }
  30656. return this._texture._sphericalPolynomial;
  30657. },
  30658. set: function (value) {
  30659. if (this._texture) {
  30660. this._texture._sphericalPolynomial = value;
  30661. }
  30662. },
  30663. enumerable: true,
  30664. configurable: true
  30665. });
  30666. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30667. get: function () {
  30668. if (this._texture) {
  30669. return this._texture._lodTextureHigh;
  30670. }
  30671. return null;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30677. get: function () {
  30678. if (this._texture) {
  30679. return this._texture._lodTextureMid;
  30680. }
  30681. return null;
  30682. },
  30683. enumerable: true,
  30684. configurable: true
  30685. });
  30686. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30687. get: function () {
  30688. if (this._texture) {
  30689. return this._texture._lodTextureLow;
  30690. }
  30691. return null;
  30692. },
  30693. enumerable: true,
  30694. configurable: true
  30695. });
  30696. BaseTexture.prototype.dispose = function () {
  30697. if (!this._scene) {
  30698. return;
  30699. }
  30700. // Animations
  30701. this._scene.stopAnimation(this);
  30702. // Remove from scene
  30703. this._scene._removePendingData(this);
  30704. var index = this._scene.textures.indexOf(this);
  30705. if (index >= 0) {
  30706. this._scene.textures.splice(index, 1);
  30707. }
  30708. if (this._texture === undefined) {
  30709. return;
  30710. }
  30711. // Release
  30712. this.releaseInternalTexture();
  30713. // Callback
  30714. this.onDisposeObservable.notifyObservers(this);
  30715. this.onDisposeObservable.clear();
  30716. };
  30717. BaseTexture.prototype.serialize = function () {
  30718. if (!this.name) {
  30719. return null;
  30720. }
  30721. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30722. // Animations
  30723. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30724. return serializationObject;
  30725. };
  30726. BaseTexture.WhenAllReady = function (textures, callback) {
  30727. var numRemaining = textures.length;
  30728. if (numRemaining === 0) {
  30729. callback();
  30730. return;
  30731. }
  30732. var _loop_1 = function () {
  30733. texture = textures[i];
  30734. if (texture.isReady()) {
  30735. if (--numRemaining === 0) {
  30736. callback();
  30737. }
  30738. }
  30739. else {
  30740. onLoadObservable = texture.onLoadObservable;
  30741. var onLoadCallback_1 = function () {
  30742. onLoadObservable.removeCallback(onLoadCallback_1);
  30743. if (--numRemaining === 0) {
  30744. callback();
  30745. }
  30746. };
  30747. onLoadObservable.add(onLoadCallback_1);
  30748. }
  30749. };
  30750. var texture, onLoadObservable;
  30751. for (var i = 0; i < textures.length; i++) {
  30752. _loop_1();
  30753. }
  30754. };
  30755. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30756. __decorate([
  30757. BABYLON.serialize()
  30758. ], BaseTexture.prototype, "name", void 0);
  30759. __decorate([
  30760. BABYLON.serialize("hasAlpha")
  30761. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], BaseTexture.prototype, "level", void 0);
  30768. __decorate([
  30769. BABYLON.serialize()
  30770. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30771. __decorate([
  30772. BABYLON.serialize("coordinatesMode")
  30773. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], BaseTexture.prototype, "wrapU", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], BaseTexture.prototype, "wrapV", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], BaseTexture.prototype, "wrapR", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], BaseTexture.prototype, "isCube", void 0);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], BaseTexture.prototype, "is3D", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], BaseTexture.prototype, "gammaSpace", void 0);
  30795. __decorate([
  30796. BABYLON.serialize()
  30797. ], BaseTexture.prototype, "invertZ", void 0);
  30798. __decorate([
  30799. BABYLON.serialize()
  30800. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30801. __decorate([
  30802. BABYLON.serialize()
  30803. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30804. __decorate([
  30805. BABYLON.serialize()
  30806. ], BaseTexture.prototype, "lodGenerationScale", null);
  30807. __decorate([
  30808. BABYLON.serialize()
  30809. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30810. return BaseTexture;
  30811. }());
  30812. BABYLON.BaseTexture = BaseTexture;
  30813. })(BABYLON || (BABYLON = {}));
  30814. //# sourceMappingURL=babylon.baseTexture.js.map
  30815. var BABYLON;
  30816. (function (BABYLON) {
  30817. var Texture = /** @class */ (function (_super) {
  30818. __extends(Texture, _super);
  30819. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30820. if (noMipmap === void 0) { noMipmap = false; }
  30821. if (invertY === void 0) { invertY = true; }
  30822. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30823. if (onLoad === void 0) { onLoad = null; }
  30824. if (onError === void 0) { onError = null; }
  30825. if (buffer === void 0) { buffer = null; }
  30826. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30827. var _this = _super.call(this, scene) || this;
  30828. _this.uOffset = 0;
  30829. _this.vOffset = 0;
  30830. _this.uScale = 1.0;
  30831. _this.vScale = 1.0;
  30832. _this.uAng = 0;
  30833. _this.vAng = 0;
  30834. _this.wAng = 0;
  30835. /**
  30836. * Defines the center of rotation (U)
  30837. */
  30838. _this.uRotationCenter = 0.5;
  30839. /**
  30840. * Defines the center of rotation (V)
  30841. */
  30842. _this.vRotationCenter = 0.5;
  30843. /**
  30844. * Defines the center of rotation (W)
  30845. */
  30846. _this.wRotationCenter = 0.5;
  30847. _this._isBlocking = true;
  30848. _this.name = url || "";
  30849. _this.url = url;
  30850. _this._noMipmap = noMipmap;
  30851. _this._invertY = invertY;
  30852. _this._samplingMode = samplingMode;
  30853. _this._buffer = buffer;
  30854. _this._deleteBuffer = deleteBuffer;
  30855. if (format) {
  30856. _this._format = format;
  30857. }
  30858. scene = _this.getScene();
  30859. if (!scene) {
  30860. return _this;
  30861. }
  30862. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30863. var load = function () {
  30864. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30865. _this.onLoadObservable.notifyObservers(_this);
  30866. }
  30867. if (onLoad) {
  30868. onLoad();
  30869. }
  30870. if (!_this.isBlocking && scene) {
  30871. scene.resetCachedMaterial();
  30872. }
  30873. };
  30874. if (!_this.url) {
  30875. _this._delayedOnLoad = load;
  30876. _this._delayedOnError = onError;
  30877. return _this;
  30878. }
  30879. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30880. if (!_this._texture) {
  30881. if (!scene.useDelayedTextureLoading) {
  30882. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30883. if (deleteBuffer) {
  30884. delete _this._buffer;
  30885. }
  30886. }
  30887. else {
  30888. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30889. _this._delayedOnLoad = load;
  30890. _this._delayedOnError = onError;
  30891. }
  30892. }
  30893. else {
  30894. if (_this._texture.isReady) {
  30895. BABYLON.Tools.SetImmediate(function () { return load(); });
  30896. }
  30897. else {
  30898. _this._texture.onLoadedObservable.add(load);
  30899. }
  30900. }
  30901. return _this;
  30902. }
  30903. Object.defineProperty(Texture.prototype, "noMipmap", {
  30904. get: function () {
  30905. return this._noMipmap;
  30906. },
  30907. enumerable: true,
  30908. configurable: true
  30909. });
  30910. Object.defineProperty(Texture.prototype, "isBlocking", {
  30911. get: function () {
  30912. return this._isBlocking;
  30913. },
  30914. set: function (value) {
  30915. this._isBlocking = value;
  30916. },
  30917. enumerable: true,
  30918. configurable: true
  30919. });
  30920. Object.defineProperty(Texture.prototype, "samplingMode", {
  30921. get: function () {
  30922. return this._samplingMode;
  30923. },
  30924. enumerable: true,
  30925. configurable: true
  30926. });
  30927. /**
  30928. * Update the url (and optional buffer) of this texture if url was null during construction.
  30929. * @param url the url of the texture
  30930. * @param buffer the buffer of the texture (defaults to null)
  30931. */
  30932. Texture.prototype.updateURL = function (url, buffer) {
  30933. if (buffer === void 0) { buffer = null; }
  30934. if (this.url) {
  30935. throw new Error("URL is already set");
  30936. }
  30937. this.url = url;
  30938. this._buffer = buffer;
  30939. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30940. this.delayLoad();
  30941. };
  30942. Texture.prototype.delayLoad = function () {
  30943. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30944. return;
  30945. }
  30946. var scene = this.getScene();
  30947. if (!scene) {
  30948. return;
  30949. }
  30950. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30951. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30952. if (!this._texture) {
  30953. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30954. if (this._deleteBuffer) {
  30955. delete this._buffer;
  30956. }
  30957. }
  30958. else {
  30959. if (this._delayedOnLoad) {
  30960. if (this._texture.isReady) {
  30961. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30962. }
  30963. else {
  30964. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30965. }
  30966. }
  30967. }
  30968. this._delayedOnLoad = null;
  30969. this._delayedOnError = null;
  30970. };
  30971. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30972. if (!this._texture) {
  30973. return;
  30974. }
  30975. var scene = this.getScene();
  30976. if (!scene) {
  30977. return;
  30978. }
  30979. this._samplingMode = samplingMode;
  30980. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30981. };
  30982. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30983. x *= this.uScale;
  30984. y *= this.vScale;
  30985. x -= this.uRotationCenter * this.uScale;
  30986. y -= this.vRotationCenter * this.vScale;
  30987. z -= this.wRotationCenter;
  30988. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30989. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30990. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30991. t.z += this.wRotationCenter;
  30992. };
  30993. Texture.prototype.getTextureMatrix = function () {
  30994. var _this = this;
  30995. if (this.uOffset === this._cachedUOffset &&
  30996. this.vOffset === this._cachedVOffset &&
  30997. this.uScale === this._cachedUScale &&
  30998. this.vScale === this._cachedVScale &&
  30999. this.uAng === this._cachedUAng &&
  31000. this.vAng === this._cachedVAng &&
  31001. this.wAng === this._cachedWAng) {
  31002. return this._cachedTextureMatrix;
  31003. }
  31004. this._cachedUOffset = this.uOffset;
  31005. this._cachedVOffset = this.vOffset;
  31006. this._cachedUScale = this.uScale;
  31007. this._cachedVScale = this.vScale;
  31008. this._cachedUAng = this.uAng;
  31009. this._cachedVAng = this.vAng;
  31010. this._cachedWAng = this.wAng;
  31011. if (!this._cachedTextureMatrix) {
  31012. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31013. this._rowGenerationMatrix = new BABYLON.Matrix();
  31014. this._t0 = BABYLON.Vector3.Zero();
  31015. this._t1 = BABYLON.Vector3.Zero();
  31016. this._t2 = BABYLON.Vector3.Zero();
  31017. }
  31018. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31019. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31020. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31021. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31022. this._t1.subtractInPlace(this._t0);
  31023. this._t2.subtractInPlace(this._t0);
  31024. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31025. this._cachedTextureMatrix.m[0] = this._t1.x;
  31026. this._cachedTextureMatrix.m[1] = this._t1.y;
  31027. this._cachedTextureMatrix.m[2] = this._t1.z;
  31028. this._cachedTextureMatrix.m[4] = this._t2.x;
  31029. this._cachedTextureMatrix.m[5] = this._t2.y;
  31030. this._cachedTextureMatrix.m[6] = this._t2.z;
  31031. this._cachedTextureMatrix.m[8] = this._t0.x;
  31032. this._cachedTextureMatrix.m[9] = this._t0.y;
  31033. this._cachedTextureMatrix.m[10] = this._t0.z;
  31034. var scene = this.getScene();
  31035. if (!scene) {
  31036. return this._cachedTextureMatrix;
  31037. }
  31038. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31039. return mat.hasTexture(_this);
  31040. });
  31041. return this._cachedTextureMatrix;
  31042. };
  31043. Texture.prototype.getReflectionTextureMatrix = function () {
  31044. var _this = this;
  31045. var scene = this.getScene();
  31046. if (!scene) {
  31047. return this._cachedTextureMatrix;
  31048. }
  31049. if (this.uOffset === this._cachedUOffset &&
  31050. this.vOffset === this._cachedVOffset &&
  31051. this.uScale === this._cachedUScale &&
  31052. this.vScale === this._cachedVScale &&
  31053. this.coordinatesMode === this._cachedCoordinatesMode) {
  31054. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31055. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31056. return this._cachedTextureMatrix;
  31057. }
  31058. }
  31059. else {
  31060. return this._cachedTextureMatrix;
  31061. }
  31062. }
  31063. if (!this._cachedTextureMatrix) {
  31064. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31065. }
  31066. if (!this._projectionModeMatrix) {
  31067. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31068. }
  31069. this._cachedUOffset = this.uOffset;
  31070. this._cachedVOffset = this.vOffset;
  31071. this._cachedUScale = this.uScale;
  31072. this._cachedVScale = this.vScale;
  31073. this._cachedCoordinatesMode = this.coordinatesMode;
  31074. switch (this.coordinatesMode) {
  31075. case Texture.PLANAR_MODE:
  31076. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31077. this._cachedTextureMatrix[0] = this.uScale;
  31078. this._cachedTextureMatrix[5] = this.vScale;
  31079. this._cachedTextureMatrix[12] = this.uOffset;
  31080. this._cachedTextureMatrix[13] = this.vOffset;
  31081. break;
  31082. case Texture.PROJECTION_MODE:
  31083. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31084. this._projectionModeMatrix.m[0] = 0.5;
  31085. this._projectionModeMatrix.m[5] = -0.5;
  31086. this._projectionModeMatrix.m[10] = 0.0;
  31087. this._projectionModeMatrix.m[12] = 0.5;
  31088. this._projectionModeMatrix.m[13] = 0.5;
  31089. this._projectionModeMatrix.m[14] = 1.0;
  31090. this._projectionModeMatrix.m[15] = 1.0;
  31091. var projectionMatrix = scene.getProjectionMatrix();
  31092. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31093. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31094. break;
  31095. default:
  31096. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31097. break;
  31098. }
  31099. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31100. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31101. });
  31102. return this._cachedTextureMatrix;
  31103. };
  31104. Texture.prototype.clone = function () {
  31105. var _this = this;
  31106. return BABYLON.SerializationHelper.Clone(function () {
  31107. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31108. }, this);
  31109. };
  31110. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31111. get: function () {
  31112. if (!this._onLoadObservable) {
  31113. this._onLoadObservable = new BABYLON.Observable();
  31114. }
  31115. return this._onLoadObservable;
  31116. },
  31117. enumerable: true,
  31118. configurable: true
  31119. });
  31120. Texture.prototype.serialize = function () {
  31121. var serializationObject = _super.prototype.serialize.call(this);
  31122. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31123. serializationObject.base64String = this._buffer;
  31124. serializationObject.name = serializationObject.name.replace("data:", "");
  31125. }
  31126. serializationObject.invertY = this._invertY;
  31127. serializationObject.samplingMode = this.samplingMode;
  31128. return serializationObject;
  31129. };
  31130. Texture.prototype.getClassName = function () {
  31131. return "Texture";
  31132. };
  31133. Texture.prototype.dispose = function () {
  31134. _super.prototype.dispose.call(this);
  31135. if (this.onLoadObservable) {
  31136. this.onLoadObservable.clear();
  31137. this._onLoadObservable = null;
  31138. }
  31139. this._delayedOnLoad = null;
  31140. this._delayedOnError = null;
  31141. };
  31142. // Statics
  31143. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31144. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31145. if (onLoad === void 0) { onLoad = null; }
  31146. if (onError === void 0) { onError = null; }
  31147. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31148. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31149. };
  31150. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31151. if (parsedTexture.customType) {
  31152. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31153. // Update Sampling Mode
  31154. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31155. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31156. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31157. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31158. }
  31159. }
  31160. return parsedCustomTexture;
  31161. }
  31162. if (parsedTexture.isCube) {
  31163. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31164. }
  31165. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31166. return null;
  31167. }
  31168. var texture = BABYLON.SerializationHelper.Parse(function () {
  31169. var generateMipMaps = true;
  31170. if (parsedTexture.noMipmap) {
  31171. generateMipMaps = false;
  31172. }
  31173. if (parsedTexture.mirrorPlane) {
  31174. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31175. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31176. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31177. return mirrorTexture;
  31178. }
  31179. else if (parsedTexture.isRenderTarget) {
  31180. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31181. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31182. return renderTargetTexture;
  31183. }
  31184. else {
  31185. var texture;
  31186. if (parsedTexture.base64String) {
  31187. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31188. }
  31189. else {
  31190. var url = rootUrl + parsedTexture.name;
  31191. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31192. url = parsedTexture.url;
  31193. }
  31194. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31195. }
  31196. return texture;
  31197. }
  31198. }, parsedTexture, scene);
  31199. // Update Sampling Mode
  31200. if (parsedTexture.samplingMode) {
  31201. var sampling = parsedTexture.samplingMode;
  31202. if (texture._samplingMode !== sampling) {
  31203. texture.updateSamplingMode(sampling);
  31204. }
  31205. }
  31206. // Animations
  31207. if (parsedTexture.animations) {
  31208. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31209. var parsedAnimation = parsedTexture.animations[animationIndex];
  31210. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31211. }
  31212. }
  31213. return texture;
  31214. };
  31215. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31216. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31217. if (noMipmap === void 0) { noMipmap = false; }
  31218. if (invertY === void 0) { invertY = true; }
  31219. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31220. if (onLoad === void 0) { onLoad = null; }
  31221. if (onError === void 0) { onError = null; }
  31222. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31223. if (name.substr(0, 5) !== "data:") {
  31224. name = "data:" + name;
  31225. }
  31226. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31227. };
  31228. // Constants
  31229. Texture.NEAREST_SAMPLINGMODE = 1;
  31230. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31231. Texture.BILINEAR_SAMPLINGMODE = 2;
  31232. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31233. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31234. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31235. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31236. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31237. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31238. Texture.NEAREST_LINEAR = 7;
  31239. Texture.NEAREST_NEAREST = 8;
  31240. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31241. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31242. Texture.LINEAR_LINEAR = 11;
  31243. Texture.LINEAR_NEAREST = 12;
  31244. Texture.EXPLICIT_MODE = 0;
  31245. Texture.SPHERICAL_MODE = 1;
  31246. Texture.PLANAR_MODE = 2;
  31247. Texture.CUBIC_MODE = 3;
  31248. Texture.PROJECTION_MODE = 4;
  31249. Texture.SKYBOX_MODE = 5;
  31250. Texture.INVCUBIC_MODE = 6;
  31251. Texture.EQUIRECTANGULAR_MODE = 7;
  31252. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31253. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31254. Texture.CLAMP_ADDRESSMODE = 0;
  31255. Texture.WRAP_ADDRESSMODE = 1;
  31256. Texture.MIRROR_ADDRESSMODE = 2;
  31257. /**
  31258. * 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
  31259. */
  31260. Texture.UseSerializedUrlIfAny = false;
  31261. __decorate([
  31262. BABYLON.serialize()
  31263. ], Texture.prototype, "url", void 0);
  31264. __decorate([
  31265. BABYLON.serialize()
  31266. ], Texture.prototype, "uOffset", void 0);
  31267. __decorate([
  31268. BABYLON.serialize()
  31269. ], Texture.prototype, "vOffset", void 0);
  31270. __decorate([
  31271. BABYLON.serialize()
  31272. ], Texture.prototype, "uScale", void 0);
  31273. __decorate([
  31274. BABYLON.serialize()
  31275. ], Texture.prototype, "vScale", void 0);
  31276. __decorate([
  31277. BABYLON.serialize()
  31278. ], Texture.prototype, "uAng", void 0);
  31279. __decorate([
  31280. BABYLON.serialize()
  31281. ], Texture.prototype, "vAng", void 0);
  31282. __decorate([
  31283. BABYLON.serialize()
  31284. ], Texture.prototype, "wAng", void 0);
  31285. __decorate([
  31286. BABYLON.serialize()
  31287. ], Texture.prototype, "uRotationCenter", void 0);
  31288. __decorate([
  31289. BABYLON.serialize()
  31290. ], Texture.prototype, "vRotationCenter", void 0);
  31291. __decorate([
  31292. BABYLON.serialize()
  31293. ], Texture.prototype, "wRotationCenter", void 0);
  31294. __decorate([
  31295. BABYLON.serialize()
  31296. ], Texture.prototype, "isBlocking", null);
  31297. return Texture;
  31298. }(BABYLON.BaseTexture));
  31299. BABYLON.Texture = Texture;
  31300. })(BABYLON || (BABYLON = {}));
  31301. //# sourceMappingURL=babylon.texture.js.map
  31302. var BABYLON;
  31303. (function (BABYLON) {
  31304. /**
  31305. * @hidden
  31306. **/
  31307. var _InstancesBatch = /** @class */ (function () {
  31308. function _InstancesBatch() {
  31309. this.mustReturn = false;
  31310. this.visibleInstances = new Array();
  31311. this.renderSelf = new Array();
  31312. }
  31313. return _InstancesBatch;
  31314. }());
  31315. BABYLON._InstancesBatch = _InstancesBatch;
  31316. var Mesh = /** @class */ (function (_super) {
  31317. __extends(Mesh, _super);
  31318. /**
  31319. * @constructor
  31320. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31321. * @param {Scene} scene The scene to add this mesh to.
  31322. * @param {Node} parent The parent of this mesh, if it has one
  31323. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31324. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31325. * When false, achieved by calling a clone(), also passing False.
  31326. * This will make creation of children, recursive.
  31327. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31328. */
  31329. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31330. if (scene === void 0) { scene = null; }
  31331. if (parent === void 0) { parent = null; }
  31332. if (source === void 0) { source = null; }
  31333. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31334. var _this = _super.call(this, name, scene) || this;
  31335. // Events
  31336. /**
  31337. * An event triggered before rendering the mesh
  31338. */
  31339. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31340. /**
  31341. * An event triggered after rendering the mesh
  31342. */
  31343. _this.onAfterRenderObservable = new BABYLON.Observable();
  31344. /**
  31345. * An event triggered before drawing the mesh
  31346. */
  31347. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31348. // Members
  31349. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31350. _this.instances = new Array();
  31351. _this._LODLevels = new Array();
  31352. _this._visibleInstances = {};
  31353. _this._renderIdForInstances = new Array();
  31354. _this._batchCache = new _InstancesBatch();
  31355. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31356. // Use by builder only to know what orientation were the mesh build in.
  31357. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31358. _this.overrideMaterialSideOrientation = null;
  31359. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31360. // Will be used to save a source mesh reference, If any
  31361. _this._source = null;
  31362. scene = _this.getScene();
  31363. if (source) {
  31364. // Geometry
  31365. if (source._geometry) {
  31366. source._geometry.applyToMesh(_this);
  31367. }
  31368. // Deep copy
  31369. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31370. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31371. // Source mesh
  31372. _this._source = source;
  31373. // Metadata
  31374. if (source.metadata && source.metadata.clone) {
  31375. _this.metadata = source.metadata.clone();
  31376. }
  31377. else {
  31378. _this.metadata = source.metadata;
  31379. }
  31380. // Tags
  31381. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31382. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31383. }
  31384. // Parent
  31385. _this.parent = source.parent;
  31386. // Pivot
  31387. _this.setPivotMatrix(source.getPivotMatrix());
  31388. _this.id = name + "." + source.id;
  31389. // Material
  31390. _this.material = source.material;
  31391. var index;
  31392. if (!doNotCloneChildren) {
  31393. // Children
  31394. var directDescendants = source.getDescendants(true);
  31395. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31396. var child = directDescendants[index_1];
  31397. if (child.clone) {
  31398. child.clone(name + "." + child.name, _this);
  31399. }
  31400. }
  31401. }
  31402. // Physics clone
  31403. var physicsEngine = _this.getScene().getPhysicsEngine();
  31404. if (clonePhysicsImpostor && physicsEngine) {
  31405. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31406. if (impostor) {
  31407. _this.physicsImpostor = impostor.clone(_this);
  31408. }
  31409. }
  31410. // Particles
  31411. for (index = 0; index < scene.particleSystems.length; index++) {
  31412. var system = scene.particleSystems[index];
  31413. if (system.emitter === source) {
  31414. system.clone(system.name, _this);
  31415. }
  31416. }
  31417. _this.computeWorldMatrix(true);
  31418. }
  31419. // Parent
  31420. if (parent !== null) {
  31421. _this.parent = parent;
  31422. }
  31423. return _this;
  31424. }
  31425. Object.defineProperty(Mesh, "FRONTSIDE", {
  31426. /**
  31427. * Mesh side orientation : usually the external or front surface
  31428. */
  31429. get: function () {
  31430. return Mesh._FRONTSIDE;
  31431. },
  31432. enumerable: true,
  31433. configurable: true
  31434. });
  31435. Object.defineProperty(Mesh, "BACKSIDE", {
  31436. /**
  31437. * Mesh side orientation : usually the internal or back surface
  31438. */
  31439. get: function () {
  31440. return Mesh._BACKSIDE;
  31441. },
  31442. enumerable: true,
  31443. configurable: true
  31444. });
  31445. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31446. /**
  31447. * Mesh side orientation : both internal and external or front and back surfaces
  31448. */
  31449. get: function () {
  31450. return Mesh._DOUBLESIDE;
  31451. },
  31452. enumerable: true,
  31453. configurable: true
  31454. });
  31455. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31456. /**
  31457. * Mesh side orientation : by default, `FRONTSIDE`
  31458. */
  31459. get: function () {
  31460. return Mesh._DEFAULTSIDE;
  31461. },
  31462. enumerable: true,
  31463. configurable: true
  31464. });
  31465. Object.defineProperty(Mesh, "NO_CAP", {
  31466. /**
  31467. * Mesh cap setting : no cap
  31468. */
  31469. get: function () {
  31470. return Mesh._NO_CAP;
  31471. },
  31472. enumerable: true,
  31473. configurable: true
  31474. });
  31475. Object.defineProperty(Mesh, "CAP_START", {
  31476. /**
  31477. * Mesh cap setting : one cap at the beginning of the mesh
  31478. */
  31479. get: function () {
  31480. return Mesh._CAP_START;
  31481. },
  31482. enumerable: true,
  31483. configurable: true
  31484. });
  31485. Object.defineProperty(Mesh, "CAP_END", {
  31486. /**
  31487. * Mesh cap setting : one cap at the end of the mesh
  31488. */
  31489. get: function () {
  31490. return Mesh._CAP_END;
  31491. },
  31492. enumerable: true,
  31493. configurable: true
  31494. });
  31495. Object.defineProperty(Mesh, "CAP_ALL", {
  31496. /**
  31497. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31498. */
  31499. get: function () {
  31500. return Mesh._CAP_ALL;
  31501. },
  31502. enumerable: true,
  31503. configurable: true
  31504. });
  31505. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31506. set: function (callback) {
  31507. if (this._onBeforeDrawObserver) {
  31508. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31509. }
  31510. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31511. },
  31512. enumerable: true,
  31513. configurable: true
  31514. });
  31515. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31516. get: function () {
  31517. return this._morphTargetManager;
  31518. },
  31519. set: function (value) {
  31520. if (this._morphTargetManager === value) {
  31521. return;
  31522. }
  31523. this._morphTargetManager = value;
  31524. this._syncGeometryWithMorphTargetManager();
  31525. },
  31526. enumerable: true,
  31527. configurable: true
  31528. });
  31529. Object.defineProperty(Mesh.prototype, "source", {
  31530. get: function () {
  31531. return this._source;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31537. get: function () {
  31538. return this._unIndexed;
  31539. },
  31540. set: function (value) {
  31541. if (this._unIndexed !== value) {
  31542. this._unIndexed = value;
  31543. this._markSubMeshesAsAttributesDirty();
  31544. }
  31545. },
  31546. enumerable: true,
  31547. configurable: true
  31548. });
  31549. // Methods
  31550. /**
  31551. * Returns the string "Mesh".
  31552. */
  31553. Mesh.prototype.getClassName = function () {
  31554. return "Mesh";
  31555. };
  31556. /**
  31557. * Returns a string.
  31558. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31559. */
  31560. Mesh.prototype.toString = function (fullDetails) {
  31561. var ret = _super.prototype.toString.call(this, fullDetails);
  31562. ret += ", n vertices: " + this.getTotalVertices();
  31563. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31564. if (this.animations) {
  31565. for (var i = 0; i < this.animations.length; i++) {
  31566. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31567. }
  31568. }
  31569. if (fullDetails) {
  31570. if (this._geometry) {
  31571. var ib = this.getIndices();
  31572. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31573. if (vb && ib) {
  31574. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31575. }
  31576. }
  31577. else {
  31578. ret += ", flat shading: UNKNOWN";
  31579. }
  31580. }
  31581. return ret;
  31582. };
  31583. Mesh.prototype._unBindEffect = function () {
  31584. _super.prototype._unBindEffect.call(this);
  31585. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31586. var instance = _a[_i];
  31587. instance._unBindEffect();
  31588. }
  31589. };
  31590. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31591. /**
  31592. * True if the mesh has some Levels Of Details (LOD).
  31593. * Returns a boolean.
  31594. */
  31595. get: function () {
  31596. return this._LODLevels.length > 0;
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. /**
  31602. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31603. * @returns an array of {BABYLON.MeshLODLevel}
  31604. */
  31605. Mesh.prototype.getLODLevels = function () {
  31606. return this._LODLevels;
  31607. };
  31608. Mesh.prototype._sortLODLevels = function () {
  31609. this._LODLevels.sort(function (a, b) {
  31610. if (a.distance < b.distance) {
  31611. return 1;
  31612. }
  31613. if (a.distance > b.distance) {
  31614. return -1;
  31615. }
  31616. return 0;
  31617. });
  31618. };
  31619. /**
  31620. * Add a mesh as LOD level triggered at the given distance.
  31621. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31622. * @param distance The distance from the center of the object to show this level
  31623. * @param mesh The mesh to be added as LOD level (can be null)
  31624. * @return This mesh (for chaining)
  31625. */
  31626. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31627. if (mesh && mesh._masterMesh) {
  31628. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31629. return this;
  31630. }
  31631. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31632. this._LODLevels.push(level);
  31633. if (mesh) {
  31634. mesh._masterMesh = this;
  31635. }
  31636. this._sortLODLevels();
  31637. return this;
  31638. };
  31639. /**
  31640. * Returns the LOD level mesh at the passed distance or null if not found.
  31641. * It is related to the method `addLODLevel(distance, mesh)`.
  31642. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31643. * Returns an object Mesh or `null`.
  31644. */
  31645. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31646. for (var index = 0; index < this._LODLevels.length; index++) {
  31647. var level = this._LODLevels[index];
  31648. if (level.distance === distance) {
  31649. return level.mesh;
  31650. }
  31651. }
  31652. return null;
  31653. };
  31654. /**
  31655. * Remove a mesh from the LOD array
  31656. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31657. * @param {Mesh} mesh The mesh to be removed.
  31658. * @return {Mesh} This mesh (for chaining)
  31659. */
  31660. Mesh.prototype.removeLODLevel = function (mesh) {
  31661. for (var index = 0; index < this._LODLevels.length; index++) {
  31662. if (this._LODLevels[index].mesh === mesh) {
  31663. this._LODLevels.splice(index, 1);
  31664. if (mesh) {
  31665. mesh._masterMesh = null;
  31666. }
  31667. }
  31668. }
  31669. this._sortLODLevels();
  31670. return this;
  31671. };
  31672. /**
  31673. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31674. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31675. */
  31676. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31677. if (!this._LODLevels || this._LODLevels.length === 0) {
  31678. return this;
  31679. }
  31680. var bSphere;
  31681. if (boundingSphere) {
  31682. bSphere = boundingSphere;
  31683. }
  31684. else {
  31685. var boundingInfo = this.getBoundingInfo();
  31686. bSphere = boundingInfo.boundingSphere;
  31687. }
  31688. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31689. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31690. if (this.onLODLevelSelection) {
  31691. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31692. }
  31693. return this;
  31694. }
  31695. for (var index = 0; index < this._LODLevels.length; index++) {
  31696. var level = this._LODLevels[index];
  31697. if (level.distance < distanceToCamera) {
  31698. if (level.mesh) {
  31699. level.mesh._preActivate();
  31700. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31701. }
  31702. if (this.onLODLevelSelection) {
  31703. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31704. }
  31705. return level.mesh;
  31706. }
  31707. }
  31708. if (this.onLODLevelSelection) {
  31709. this.onLODLevelSelection(distanceToCamera, this, this);
  31710. }
  31711. return this;
  31712. };
  31713. Object.defineProperty(Mesh.prototype, "geometry", {
  31714. /**
  31715. * Returns the mesh internal Geometry object.
  31716. */
  31717. get: function () {
  31718. return this._geometry;
  31719. },
  31720. enumerable: true,
  31721. configurable: true
  31722. });
  31723. /**
  31724. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31725. */
  31726. Mesh.prototype.getTotalVertices = function () {
  31727. if (this._geometry === null || this._geometry === undefined) {
  31728. return 0;
  31729. }
  31730. return this._geometry.getTotalVertices();
  31731. };
  31732. /**
  31733. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31734. * 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.
  31735. * You can force the copy with forceCopy === true
  31736. * Returns null if the mesh has no geometry or no vertex buffer.
  31737. * Possible `kind` values :
  31738. * - BABYLON.VertexBuffer.PositionKind
  31739. * - BABYLON.VertexBuffer.UVKind
  31740. * - BABYLON.VertexBuffer.UV2Kind
  31741. * - BABYLON.VertexBuffer.UV3Kind
  31742. * - BABYLON.VertexBuffer.UV4Kind
  31743. * - BABYLON.VertexBuffer.UV5Kind
  31744. * - BABYLON.VertexBuffer.UV6Kind
  31745. * - BABYLON.VertexBuffer.ColorKind
  31746. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31747. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31748. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31749. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31750. */
  31751. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31752. if (!this._geometry) {
  31753. return null;
  31754. }
  31755. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31756. };
  31757. /**
  31758. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31759. * Returns `null` if the mesh has no geometry.
  31760. * Possible `kind` values :
  31761. * - BABYLON.VertexBuffer.PositionKind
  31762. * - BABYLON.VertexBuffer.UVKind
  31763. * - BABYLON.VertexBuffer.UV2Kind
  31764. * - BABYLON.VertexBuffer.UV3Kind
  31765. * - BABYLON.VertexBuffer.UV4Kind
  31766. * - BABYLON.VertexBuffer.UV5Kind
  31767. * - BABYLON.VertexBuffer.UV6Kind
  31768. * - BABYLON.VertexBuffer.ColorKind
  31769. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31770. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31771. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31772. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31773. */
  31774. Mesh.prototype.getVertexBuffer = function (kind) {
  31775. if (!this._geometry) {
  31776. return null;
  31777. }
  31778. return this._geometry.getVertexBuffer(kind);
  31779. };
  31780. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31781. if (!this._geometry) {
  31782. if (this._delayInfo) {
  31783. return this._delayInfo.indexOf(kind) !== -1;
  31784. }
  31785. return false;
  31786. }
  31787. return this._geometry.isVerticesDataPresent(kind);
  31788. };
  31789. /**
  31790. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31791. * Possible `kind` values :
  31792. * - BABYLON.VertexBuffer.PositionKind
  31793. * - BABYLON.VertexBuffer.UVKind
  31794. * - BABYLON.VertexBuffer.UV2Kind
  31795. * - BABYLON.VertexBuffer.UV3Kind
  31796. * - BABYLON.VertexBuffer.UV4Kind
  31797. * - BABYLON.VertexBuffer.UV5Kind
  31798. * - BABYLON.VertexBuffer.UV6Kind
  31799. * - BABYLON.VertexBuffer.ColorKind
  31800. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31801. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31802. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31803. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31804. */
  31805. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31806. if (!this._geometry) {
  31807. if (this._delayInfo) {
  31808. return this._delayInfo.indexOf(kind) !== -1;
  31809. }
  31810. return false;
  31811. }
  31812. return this._geometry.isVertexBufferUpdatable(kind);
  31813. };
  31814. /**
  31815. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31816. * Possible `kind` values :
  31817. * - BABYLON.VertexBuffer.PositionKind
  31818. * - BABYLON.VertexBuffer.UVKind
  31819. * - BABYLON.VertexBuffer.UV2Kind
  31820. * - BABYLON.VertexBuffer.UV3Kind
  31821. * - BABYLON.VertexBuffer.UV4Kind
  31822. * - BABYLON.VertexBuffer.UV5Kind
  31823. * - BABYLON.VertexBuffer.UV6Kind
  31824. * - BABYLON.VertexBuffer.ColorKind
  31825. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31826. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31827. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31828. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31829. */
  31830. Mesh.prototype.getVerticesDataKinds = function () {
  31831. if (!this._geometry) {
  31832. var result = new Array();
  31833. if (this._delayInfo) {
  31834. this._delayInfo.forEach(function (kind, index, array) {
  31835. result.push(kind);
  31836. });
  31837. }
  31838. return result;
  31839. }
  31840. return this._geometry.getVerticesDataKinds();
  31841. };
  31842. /**
  31843. * Returns a positive integer : the total number of indices in this mesh geometry.
  31844. * Returns zero if the mesh has no geometry.
  31845. */
  31846. Mesh.prototype.getTotalIndices = function () {
  31847. if (!this._geometry) {
  31848. return 0;
  31849. }
  31850. return this._geometry.getTotalIndices();
  31851. };
  31852. /**
  31853. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31854. * 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.
  31855. * Returns an empty array if the mesh has no geometry.
  31856. */
  31857. Mesh.prototype.getIndices = function (copyWhenShared) {
  31858. if (!this._geometry) {
  31859. return [];
  31860. }
  31861. return this._geometry.getIndices(copyWhenShared);
  31862. };
  31863. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31864. get: function () {
  31865. return this._masterMesh !== null && this._masterMesh !== undefined;
  31866. },
  31867. enumerable: true,
  31868. configurable: true
  31869. });
  31870. /**
  31871. * Determine if the current mesh is ready to be rendered
  31872. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31873. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31874. * @returns true if all associated assets are ready (material, textures, shaders)
  31875. */
  31876. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31877. if (completeCheck === void 0) { completeCheck = false; }
  31878. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31879. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31880. return false;
  31881. }
  31882. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31883. return false;
  31884. }
  31885. if (!this.subMeshes || this.subMeshes.length === 0) {
  31886. return true;
  31887. }
  31888. if (!completeCheck) {
  31889. return true;
  31890. }
  31891. var engine = this.getEngine();
  31892. var scene = this.getScene();
  31893. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31894. this.computeWorldMatrix();
  31895. var mat = this.material || scene.defaultMaterial;
  31896. if (mat) {
  31897. if (mat.storeEffectOnSubMeshes) {
  31898. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31899. var subMesh = _a[_i];
  31900. var effectiveMaterial = subMesh.getMaterial();
  31901. if (effectiveMaterial) {
  31902. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31903. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31904. return false;
  31905. }
  31906. }
  31907. else {
  31908. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31909. return false;
  31910. }
  31911. }
  31912. }
  31913. }
  31914. }
  31915. else {
  31916. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31917. return false;
  31918. }
  31919. }
  31920. }
  31921. // Shadows
  31922. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31923. var light = _c[_b];
  31924. var generator = light.getShadowGenerator();
  31925. if (generator) {
  31926. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31927. var subMesh = _e[_d];
  31928. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31929. return false;
  31930. }
  31931. }
  31932. }
  31933. }
  31934. // LOD
  31935. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31936. var lod = _g[_f];
  31937. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31938. return false;
  31939. }
  31940. }
  31941. return true;
  31942. };
  31943. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31944. /**
  31945. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31946. * This property is pertinent only for updatable parametric shapes.
  31947. */
  31948. get: function () {
  31949. return this._areNormalsFrozen;
  31950. },
  31951. enumerable: true,
  31952. configurable: true
  31953. });
  31954. /**
  31955. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31956. * It has no effect at all on other shapes.
  31957. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31958. * Returns the Mesh.
  31959. */
  31960. Mesh.prototype.freezeNormals = function () {
  31961. this._areNormalsFrozen = true;
  31962. return this;
  31963. };
  31964. /**
  31965. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31966. * It has no effect at all on other shapes.
  31967. * It reactivates the mesh normals computation if it was previously frozen.
  31968. * Returns the Mesh.
  31969. */
  31970. Mesh.prototype.unfreezeNormals = function () {
  31971. this._areNormalsFrozen = false;
  31972. return this;
  31973. };
  31974. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31975. /**
  31976. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31977. */
  31978. set: function (count) {
  31979. this._overridenInstanceCount = count;
  31980. },
  31981. enumerable: true,
  31982. configurable: true
  31983. });
  31984. // Methods
  31985. Mesh.prototype._preActivate = function () {
  31986. var sceneRenderId = this.getScene().getRenderId();
  31987. if (this._preActivateId === sceneRenderId) {
  31988. return this;
  31989. }
  31990. this._preActivateId = sceneRenderId;
  31991. this._visibleInstances = null;
  31992. return this;
  31993. };
  31994. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31995. if (this._visibleInstances) {
  31996. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31997. }
  31998. return this;
  31999. };
  32000. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32001. if (!this._visibleInstances) {
  32002. this._visibleInstances = {};
  32003. this._visibleInstances.defaultRenderId = renderId;
  32004. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32005. }
  32006. if (!this._visibleInstances[renderId]) {
  32007. this._visibleInstances[renderId] = new Array();
  32008. }
  32009. this._visibleInstances[renderId].push(instance);
  32010. return this;
  32011. };
  32012. /**
  32013. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32014. * This means the mesh underlying bounding box and sphere are recomputed.
  32015. * Returns the Mesh.
  32016. */
  32017. Mesh.prototype.refreshBoundingInfo = function () {
  32018. return this._refreshBoundingInfo(false);
  32019. };
  32020. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32021. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32022. return this;
  32023. }
  32024. var data = this._getPositionData(applySkeleton);
  32025. if (data) {
  32026. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32027. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32028. }
  32029. if (this.subMeshes) {
  32030. for (var index = 0; index < this.subMeshes.length; index++) {
  32031. this.subMeshes[index].refreshBoundingInfo();
  32032. }
  32033. }
  32034. this._updateBoundingInfo();
  32035. return this;
  32036. };
  32037. Mesh.prototype._getPositionData = function (applySkeleton) {
  32038. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32039. if (data && applySkeleton && this.skeleton) {
  32040. data = BABYLON.Tools.Slice(data);
  32041. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32042. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32043. if (matricesWeightsData && matricesIndicesData) {
  32044. var needExtras = this.numBoneInfluencers > 4;
  32045. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32046. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32047. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32048. var tempVector = BABYLON.Tmp.Vector3[0];
  32049. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32050. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32051. var matWeightIdx = 0;
  32052. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32053. finalMatrix.reset();
  32054. var inf;
  32055. var weight;
  32056. for (inf = 0; inf < 4; inf++) {
  32057. weight = matricesWeightsData[matWeightIdx + inf];
  32058. if (weight <= 0)
  32059. break;
  32060. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32061. finalMatrix.addToSelf(tempMatrix);
  32062. }
  32063. if (needExtras) {
  32064. for (inf = 0; inf < 4; inf++) {
  32065. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32066. if (weight <= 0)
  32067. break;
  32068. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32069. finalMatrix.addToSelf(tempMatrix);
  32070. }
  32071. }
  32072. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32073. tempVector.toArray(data, index);
  32074. }
  32075. }
  32076. }
  32077. return data;
  32078. };
  32079. Mesh.prototype._createGlobalSubMesh = function (force) {
  32080. var totalVertices = this.getTotalVertices();
  32081. if (!totalVertices || !this.getIndices()) {
  32082. return null;
  32083. }
  32084. // Check if we need to recreate the submeshes
  32085. if (this.subMeshes && this.subMeshes.length > 0) {
  32086. var ib = this.getIndices();
  32087. if (!ib) {
  32088. return null;
  32089. }
  32090. var totalIndices = ib.length;
  32091. var needToRecreate = false;
  32092. if (force) {
  32093. needToRecreate = true;
  32094. }
  32095. else {
  32096. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32097. var submesh = _a[_i];
  32098. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32099. needToRecreate = true;
  32100. break;
  32101. }
  32102. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32103. needToRecreate = true;
  32104. break;
  32105. }
  32106. }
  32107. }
  32108. if (!needToRecreate) {
  32109. return this.subMeshes[0];
  32110. }
  32111. }
  32112. this.releaseSubMeshes();
  32113. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32114. };
  32115. Mesh.prototype.subdivide = function (count) {
  32116. if (count < 1) {
  32117. return;
  32118. }
  32119. var totalIndices = this.getTotalIndices();
  32120. var subdivisionSize = (totalIndices / count) | 0;
  32121. var offset = 0;
  32122. // Ensure that subdivisionSize is a multiple of 3
  32123. while (subdivisionSize % 3 !== 0) {
  32124. subdivisionSize++;
  32125. }
  32126. this.releaseSubMeshes();
  32127. for (var index = 0; index < count; index++) {
  32128. if (offset >= totalIndices) {
  32129. break;
  32130. }
  32131. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32132. offset += subdivisionSize;
  32133. }
  32134. this.synchronizeInstances();
  32135. };
  32136. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32137. if (updatable === void 0) { updatable = false; }
  32138. if (!this._geometry) {
  32139. var vertexData = new BABYLON.VertexData();
  32140. vertexData.set(data, kind);
  32141. var scene = this.getScene();
  32142. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32143. }
  32144. else {
  32145. this._geometry.setVerticesData(kind, data, updatable, stride);
  32146. }
  32147. return this;
  32148. };
  32149. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32150. if (updatable === void 0) { updatable = true; }
  32151. var vb = this.getVertexBuffer(kind);
  32152. if (!vb || vb.isUpdatable() === updatable) {
  32153. return;
  32154. }
  32155. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32156. };
  32157. /**
  32158. * Sets the mesh VertexBuffer.
  32159. * Returns the Mesh.
  32160. */
  32161. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32162. if (!this._geometry) {
  32163. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32164. }
  32165. this._geometry.setVerticesBuffer(buffer);
  32166. return this;
  32167. };
  32168. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32169. if (!this._geometry) {
  32170. return this;
  32171. }
  32172. if (!makeItUnique) {
  32173. this._geometry.updateVerticesData(kind, data, updateExtends);
  32174. }
  32175. else {
  32176. this.makeGeometryUnique();
  32177. this.updateVerticesData(kind, data, updateExtends, false);
  32178. }
  32179. return this;
  32180. };
  32181. /**
  32182. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32183. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32184. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32185. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32186. * Returns the Mesh.
  32187. */
  32188. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32189. if (computeNormals === void 0) { computeNormals = true; }
  32190. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32191. if (!positions) {
  32192. return this;
  32193. }
  32194. positionFunction(positions);
  32195. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32196. if (computeNormals) {
  32197. var indices = this.getIndices();
  32198. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32199. if (!normals) {
  32200. return this;
  32201. }
  32202. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32203. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32204. }
  32205. return this;
  32206. };
  32207. /**
  32208. * Creates a un-shared specific occurence of the geometry for the mesh.
  32209. * Returns the Mesh.
  32210. */
  32211. Mesh.prototype.makeGeometryUnique = function () {
  32212. if (!this._geometry) {
  32213. return this;
  32214. }
  32215. var oldGeometry = this._geometry;
  32216. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32217. oldGeometry.releaseForMesh(this, true);
  32218. geometry.applyToMesh(this);
  32219. return this;
  32220. };
  32221. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32222. if (totalVertices === void 0) { totalVertices = null; }
  32223. if (updatable === void 0) { updatable = false; }
  32224. if (!this._geometry) {
  32225. var vertexData = new BABYLON.VertexData();
  32226. vertexData.indices = indices;
  32227. var scene = this.getScene();
  32228. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32229. }
  32230. else {
  32231. this._geometry.setIndices(indices, totalVertices, updatable);
  32232. }
  32233. return this;
  32234. };
  32235. /**
  32236. * Update the current index buffer
  32237. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32238. * Returns the Mesh.
  32239. */
  32240. Mesh.prototype.updateIndices = function (indices, offset) {
  32241. if (!this._geometry) {
  32242. return this;
  32243. }
  32244. this._geometry.updateIndices(indices, offset);
  32245. return this;
  32246. };
  32247. /**
  32248. * Invert the geometry to move from a right handed system to a left handed one.
  32249. * Returns the Mesh.
  32250. */
  32251. Mesh.prototype.toLeftHanded = function () {
  32252. if (!this._geometry) {
  32253. return this;
  32254. }
  32255. this._geometry.toLeftHanded();
  32256. return this;
  32257. };
  32258. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32259. if (!this._geometry) {
  32260. return this;
  32261. }
  32262. var engine = this.getScene().getEngine();
  32263. // Wireframe
  32264. var indexToBind;
  32265. if (this._unIndexed) {
  32266. indexToBind = null;
  32267. }
  32268. else {
  32269. switch (fillMode) {
  32270. case BABYLON.Material.PointFillMode:
  32271. indexToBind = null;
  32272. break;
  32273. case BABYLON.Material.WireFrameFillMode:
  32274. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32275. break;
  32276. default:
  32277. case BABYLON.Material.TriangleFillMode:
  32278. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32279. break;
  32280. }
  32281. }
  32282. // VBOs
  32283. this._geometry._bind(effect, indexToBind);
  32284. return this;
  32285. };
  32286. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32287. if (alternate === void 0) { alternate = false; }
  32288. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32289. return this;
  32290. }
  32291. this.onBeforeDrawObservable.notifyObservers(this);
  32292. var scene = this.getScene();
  32293. var engine = scene.getEngine();
  32294. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32295. // or triangles as points
  32296. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32297. }
  32298. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32299. // Triangles as wireframe
  32300. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32301. }
  32302. else {
  32303. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32304. }
  32305. if (scene._isAlternateRenderingEnabled && !alternate) {
  32306. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32307. if (!effect || !scene.activeCamera) {
  32308. return this;
  32309. }
  32310. scene._switchToAlternateCameraConfiguration(true);
  32311. this._effectiveMaterial.bindView(effect);
  32312. this._effectiveMaterial.bindViewProjection(effect);
  32313. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32314. this._draw(subMesh, fillMode, instancesCount, true);
  32315. engine.setViewport(scene.activeCamera.viewport);
  32316. scene._switchToAlternateCameraConfiguration(false);
  32317. this._effectiveMaterial.bindView(effect);
  32318. this._effectiveMaterial.bindViewProjection(effect);
  32319. }
  32320. return this;
  32321. };
  32322. /**
  32323. * Registers for this mesh a javascript function called just before the rendering process.
  32324. * This function is passed the current mesh.
  32325. * Return the Mesh.
  32326. */
  32327. Mesh.prototype.registerBeforeRender = function (func) {
  32328. this.onBeforeRenderObservable.add(func);
  32329. return this;
  32330. };
  32331. /**
  32332. * Disposes a previously registered javascript function called before the rendering.
  32333. * This function is passed the current mesh.
  32334. * Returns the Mesh.
  32335. */
  32336. Mesh.prototype.unregisterBeforeRender = function (func) {
  32337. this.onBeforeRenderObservable.removeCallback(func);
  32338. return this;
  32339. };
  32340. /**
  32341. * Registers for this mesh a javascript function called just after the rendering is complete.
  32342. * This function is passed the current mesh.
  32343. * Returns the Mesh.
  32344. */
  32345. Mesh.prototype.registerAfterRender = function (func) {
  32346. this.onAfterRenderObservable.add(func);
  32347. return this;
  32348. };
  32349. /**
  32350. * Disposes a previously registered javascript function called after the rendering.
  32351. * This function is passed the current mesh.
  32352. * Return the Mesh.
  32353. */
  32354. Mesh.prototype.unregisterAfterRender = function (func) {
  32355. this.onAfterRenderObservable.removeCallback(func);
  32356. return this;
  32357. };
  32358. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32359. var scene = this.getScene();
  32360. this._batchCache.mustReturn = false;
  32361. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32362. this._batchCache.visibleInstances[subMeshId] = null;
  32363. if (this._visibleInstances) {
  32364. var currentRenderId = scene.getRenderId();
  32365. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32366. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32367. var selfRenderId = this._renderId;
  32368. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32369. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32370. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32371. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32372. }
  32373. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32374. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32375. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32376. this._batchCache.mustReturn = true;
  32377. return this._batchCache;
  32378. }
  32379. if (currentRenderId !== selfRenderId) {
  32380. this._batchCache.renderSelf[subMeshId] = false;
  32381. }
  32382. }
  32383. this._renderIdForInstances[subMeshId] = currentRenderId;
  32384. }
  32385. return this._batchCache;
  32386. };
  32387. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32388. var visibleInstances = batch.visibleInstances[subMesh._id];
  32389. if (!visibleInstances) {
  32390. return this;
  32391. }
  32392. var matricesCount = visibleInstances.length + 1;
  32393. var bufferSize = matricesCount * 16 * 4;
  32394. var currentInstancesBufferSize = this._instancesBufferSize;
  32395. var instancesBuffer = this._instancesBuffer;
  32396. while (this._instancesBufferSize < bufferSize) {
  32397. this._instancesBufferSize *= 2;
  32398. }
  32399. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32400. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32401. }
  32402. var offset = 0;
  32403. var instancesCount = 0;
  32404. var world = this.getWorldMatrix();
  32405. if (batch.renderSelf[subMesh._id]) {
  32406. world.copyToArray(this._instancesData, offset);
  32407. offset += 16;
  32408. instancesCount++;
  32409. }
  32410. if (visibleInstances) {
  32411. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32412. var instance = visibleInstances[instanceIndex];
  32413. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32414. offset += 16;
  32415. instancesCount++;
  32416. }
  32417. }
  32418. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32419. if (instancesBuffer) {
  32420. instancesBuffer.dispose();
  32421. }
  32422. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32423. this._instancesBuffer = instancesBuffer;
  32424. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32425. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32426. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32427. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32428. }
  32429. else {
  32430. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32431. }
  32432. this._bind(subMesh, effect, fillMode);
  32433. this._draw(subMesh, fillMode, instancesCount);
  32434. engine.unbindInstanceAttributes();
  32435. return this;
  32436. };
  32437. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32438. var scene = this.getScene();
  32439. var engine = scene.getEngine();
  32440. if (hardwareInstancedRendering) {
  32441. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32442. }
  32443. else {
  32444. if (batch.renderSelf[subMesh._id]) {
  32445. // Draw
  32446. if (onBeforeDraw) {
  32447. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32448. }
  32449. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32450. }
  32451. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32452. if (visibleInstancesForSubMesh) {
  32453. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32454. var instance = visibleInstancesForSubMesh[instanceIndex];
  32455. // World
  32456. var world = instance.getWorldMatrix();
  32457. if (onBeforeDraw) {
  32458. onBeforeDraw(true, world, effectiveMaterial);
  32459. }
  32460. // Draw
  32461. this._draw(subMesh, fillMode);
  32462. }
  32463. }
  32464. }
  32465. return this;
  32466. };
  32467. /**
  32468. * Triggers the draw call for the mesh.
  32469. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32470. * Returns the Mesh.
  32471. */
  32472. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32473. this._checkOcclusionQuery();
  32474. if (this._isOccluded) {
  32475. return this;
  32476. }
  32477. var scene = this.getScene();
  32478. // Managing instances
  32479. var batch = this._getInstancesRenderList(subMesh._id);
  32480. if (batch.mustReturn) {
  32481. return this;
  32482. }
  32483. // Checking geometry state
  32484. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32485. return this;
  32486. }
  32487. this.onBeforeRenderObservable.notifyObservers(this);
  32488. var engine = scene.getEngine();
  32489. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32490. // Material
  32491. var material = subMesh.getMaterial();
  32492. if (!material) {
  32493. return this;
  32494. }
  32495. this._effectiveMaterial = material;
  32496. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32497. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32498. return this;
  32499. }
  32500. }
  32501. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32502. return this;
  32503. }
  32504. // Alpha mode
  32505. if (enableAlphaMode) {
  32506. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32507. }
  32508. // Outline - step 1
  32509. var savedDepthWrite = engine.getDepthWrite();
  32510. if (this.renderOutline) {
  32511. engine.setDepthWrite(false);
  32512. scene.getOutlineRenderer().render(subMesh, batch);
  32513. engine.setDepthWrite(savedDepthWrite);
  32514. }
  32515. var effect;
  32516. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32517. effect = subMesh.effect;
  32518. }
  32519. else {
  32520. effect = this._effectiveMaterial.getEffect();
  32521. }
  32522. if (!effect) {
  32523. return this;
  32524. }
  32525. var sideOrientation = this.overrideMaterialSideOrientation;
  32526. if (sideOrientation == null) {
  32527. sideOrientation = this._effectiveMaterial.sideOrientation;
  32528. if (this._getWorldMatrixDeterminant() < 0) {
  32529. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32530. }
  32531. }
  32532. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32533. if (this._effectiveMaterial.forceDepthWrite) {
  32534. engine.setDepthWrite(true);
  32535. }
  32536. // Bind
  32537. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32538. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32539. this._bind(subMesh, effect, fillMode);
  32540. }
  32541. var world = this.getWorldMatrix();
  32542. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32543. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32544. }
  32545. else {
  32546. this._effectiveMaterial.bind(world, this);
  32547. }
  32548. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32549. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32550. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32551. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32552. }
  32553. // Draw
  32554. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32555. // Unbind
  32556. this._effectiveMaterial.unbind();
  32557. // Outline - step 2
  32558. if (this.renderOutline && savedDepthWrite) {
  32559. engine.setDepthWrite(true);
  32560. engine.setColorWrite(false);
  32561. scene.getOutlineRenderer().render(subMesh, batch);
  32562. engine.setColorWrite(true);
  32563. }
  32564. // Overlay
  32565. if (this.renderOverlay) {
  32566. var currentMode = engine.getAlphaMode();
  32567. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32568. scene.getOutlineRenderer().render(subMesh, batch, true);
  32569. engine.setAlphaMode(currentMode);
  32570. }
  32571. this.onAfterRenderObservable.notifyObservers(this);
  32572. return this;
  32573. };
  32574. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32575. if (isInstance && effectiveMaterial) {
  32576. effectiveMaterial.bindOnlyWorldMatrix(world);
  32577. }
  32578. };
  32579. /**
  32580. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32581. */
  32582. Mesh.prototype.getEmittedParticleSystems = function () {
  32583. var results = new Array();
  32584. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32585. var particleSystem = this.getScene().particleSystems[index];
  32586. if (particleSystem.emitter === this) {
  32587. results.push(particleSystem);
  32588. }
  32589. }
  32590. return results;
  32591. };
  32592. /**
  32593. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32594. */
  32595. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32596. var results = new Array();
  32597. var descendants = this.getDescendants();
  32598. descendants.push(this);
  32599. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32600. var particleSystem = this.getScene().particleSystems[index];
  32601. var emitter = particleSystem.emitter;
  32602. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32603. results.push(particleSystem);
  32604. }
  32605. }
  32606. return results;
  32607. };
  32608. /**
  32609. * Normalize matrix weights so that all vertices have a total weight set to 1
  32610. */
  32611. Mesh.prototype.cleanMatrixWeights = function () {
  32612. var epsilon = 1e-3;
  32613. var noInfluenceBoneIndex = 0.0;
  32614. if (this.skeleton) {
  32615. noInfluenceBoneIndex = this.skeleton.bones.length;
  32616. }
  32617. else {
  32618. return;
  32619. }
  32620. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32621. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32622. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32623. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32624. var influencers = this.numBoneInfluencers;
  32625. var size = matricesWeights.length;
  32626. for (var i = 0; i < size; i += 4) {
  32627. var weight = 0.0;
  32628. var firstZeroWeight = -1;
  32629. for (var j = 0; j < 4; j++) {
  32630. var w = matricesWeights[i + j];
  32631. weight += w;
  32632. if (w < epsilon && firstZeroWeight < 0) {
  32633. firstZeroWeight = j;
  32634. }
  32635. }
  32636. if (matricesWeightsExtra) {
  32637. for (var j = 0; j < 4; j++) {
  32638. var w = matricesWeightsExtra[i + j];
  32639. weight += w;
  32640. if (w < epsilon && firstZeroWeight < 0) {
  32641. firstZeroWeight = j + 4;
  32642. }
  32643. }
  32644. }
  32645. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32646. firstZeroWeight = influencers - 1;
  32647. }
  32648. if (weight > epsilon) {
  32649. var mweight = 1.0 / weight;
  32650. for (var j = 0; j < 4; j++) {
  32651. matricesWeights[i + j] *= mweight;
  32652. }
  32653. if (matricesWeightsExtra) {
  32654. for (var j = 0; j < 4; j++) {
  32655. matricesWeightsExtra[i + j] *= mweight;
  32656. }
  32657. }
  32658. }
  32659. else {
  32660. if (firstZeroWeight >= 4) {
  32661. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32662. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32663. }
  32664. else {
  32665. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32666. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32667. }
  32668. }
  32669. }
  32670. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32671. if (matricesIndicesExtra) {
  32672. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32673. }
  32674. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32675. if (matricesWeightsExtra) {
  32676. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32677. }
  32678. };
  32679. Mesh.prototype._checkDelayState = function () {
  32680. var scene = this.getScene();
  32681. if (this._geometry) {
  32682. this._geometry.load(scene);
  32683. }
  32684. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32686. this._queueLoad(scene);
  32687. }
  32688. return this;
  32689. };
  32690. Mesh.prototype._queueLoad = function (scene) {
  32691. var _this = this;
  32692. scene._addPendingData(this);
  32693. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32694. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32695. if (data instanceof ArrayBuffer) {
  32696. _this._delayLoadingFunction(data, _this);
  32697. }
  32698. else {
  32699. _this._delayLoadingFunction(JSON.parse(data), _this);
  32700. }
  32701. _this.instances.forEach(function (instance) {
  32702. instance._syncSubMeshes();
  32703. });
  32704. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32705. scene._removePendingData(_this);
  32706. }, function () { }, scene.database, getBinaryData);
  32707. return this;
  32708. };
  32709. /**
  32710. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32711. */
  32712. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32713. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32714. return false;
  32715. }
  32716. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32717. return false;
  32718. }
  32719. this._checkDelayState();
  32720. return true;
  32721. };
  32722. /**
  32723. * Sets the mesh material by the material or multiMaterial `id` property.
  32724. * The material `id` is a string identifying the material or the multiMaterial.
  32725. * This method returns the Mesh.
  32726. */
  32727. Mesh.prototype.setMaterialByID = function (id) {
  32728. var materials = this.getScene().materials;
  32729. var index;
  32730. for (index = materials.length - 1; index > -1; index--) {
  32731. if (materials[index].id === id) {
  32732. this.material = materials[index];
  32733. return this;
  32734. }
  32735. }
  32736. // Multi
  32737. var multiMaterials = this.getScene().multiMaterials;
  32738. for (index = multiMaterials.length - 1; index > -1; index--) {
  32739. if (multiMaterials[index].id === id) {
  32740. this.material = multiMaterials[index];
  32741. return this;
  32742. }
  32743. }
  32744. return this;
  32745. };
  32746. /**
  32747. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32748. */
  32749. Mesh.prototype.getAnimatables = function () {
  32750. var results = new Array();
  32751. if (this.material) {
  32752. results.push(this.material);
  32753. }
  32754. if (this.skeleton) {
  32755. results.push(this.skeleton);
  32756. }
  32757. return results;
  32758. };
  32759. /**
  32760. * Modifies the mesh geometry according to the passed transformation matrix.
  32761. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32762. * The mesh normals are modified accordingly the same transformation.
  32763. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32764. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32765. * Returns the Mesh.
  32766. */
  32767. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32768. // Position
  32769. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32770. return this;
  32771. }
  32772. var submeshes = this.subMeshes.splice(0);
  32773. this._resetPointsArrayCache();
  32774. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32775. var temp = new Array();
  32776. var index;
  32777. for (index = 0; index < data.length; index += 3) {
  32778. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32779. }
  32780. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32781. // Normals
  32782. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32783. return this;
  32784. }
  32785. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32786. temp = [];
  32787. for (index = 0; index < data.length; index += 3) {
  32788. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32789. }
  32790. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32791. // flip faces?
  32792. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32793. this.flipFaces();
  32794. }
  32795. // Restore submeshes
  32796. this.releaseSubMeshes();
  32797. this.subMeshes = submeshes;
  32798. return this;
  32799. };
  32800. /**
  32801. * Modifies the mesh geometry according to its own current World Matrix.
  32802. * The mesh World Matrix is then reset.
  32803. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32804. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32805. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32806. * Returns the Mesh.
  32807. */
  32808. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32809. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32810. this.scaling.copyFromFloats(1, 1, 1);
  32811. this.position.copyFromFloats(0, 0, 0);
  32812. this.rotation.copyFromFloats(0, 0, 0);
  32813. //only if quaternion is already set
  32814. if (this.rotationQuaternion) {
  32815. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32816. }
  32817. this._worldMatrix = BABYLON.Matrix.Identity();
  32818. return this;
  32819. };
  32820. Object.defineProperty(Mesh.prototype, "_positions", {
  32821. // Cache
  32822. get: function () {
  32823. if (this._geometry) {
  32824. return this._geometry._positions;
  32825. }
  32826. return null;
  32827. },
  32828. enumerable: true,
  32829. configurable: true
  32830. });
  32831. Mesh.prototype._resetPointsArrayCache = function () {
  32832. if (this._geometry) {
  32833. this._geometry._resetPointsArrayCache();
  32834. }
  32835. return this;
  32836. };
  32837. Mesh.prototype._generatePointsArray = function () {
  32838. if (this._geometry) {
  32839. return this._geometry._generatePointsArray();
  32840. }
  32841. return false;
  32842. };
  32843. /**
  32844. * Returns a new Mesh object generated from the current mesh properties.
  32845. * This method must not get confused with createInstance().
  32846. * The parameter `name` is a string, the name given to the new mesh.
  32847. * The optional parameter `newParent` can be any Node object (default `null`).
  32848. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32849. * 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.
  32850. */
  32851. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32852. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32853. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32854. };
  32855. /**
  32856. * Releases resources associated with this mesh.
  32857. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32858. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32859. */
  32860. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32861. var _this = this;
  32862. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32863. this.morphTargetManager = null;
  32864. if (this._geometry) {
  32865. this._geometry.releaseForMesh(this, true);
  32866. }
  32867. // Sources
  32868. var meshes = this.getScene().meshes;
  32869. meshes.forEach(function (abstractMesh) {
  32870. var mesh = abstractMesh;
  32871. if (mesh._source && mesh._source === _this) {
  32872. mesh._source = null;
  32873. }
  32874. });
  32875. this._source = null;
  32876. // Instances
  32877. if (this._instancesBuffer) {
  32878. this._instancesBuffer.dispose();
  32879. this._instancesBuffer = null;
  32880. }
  32881. while (this.instances.length) {
  32882. this.instances[0].dispose();
  32883. }
  32884. // Effect layers.
  32885. var effectLayers = this.getScene().effectLayers;
  32886. for (var i = 0; i < effectLayers.length; i++) {
  32887. var effectLayer = effectLayers[i];
  32888. if (effectLayer) {
  32889. effectLayer._disposeMesh(this);
  32890. }
  32891. }
  32892. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32893. };
  32894. /**
  32895. * Modifies the mesh geometry according to a displacement map.
  32896. * 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.
  32897. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32898. * This method returns nothing.
  32899. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32900. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32901. * 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.
  32902. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32903. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32904. *
  32905. * Returns the Mesh.
  32906. */
  32907. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32908. var _this = this;
  32909. var scene = this.getScene();
  32910. var onload = function (img) {
  32911. // Getting height map data
  32912. var canvas = document.createElement("canvas");
  32913. var context = canvas.getContext("2d");
  32914. var heightMapWidth = img.width;
  32915. var heightMapHeight = img.height;
  32916. canvas.width = heightMapWidth;
  32917. canvas.height = heightMapHeight;
  32918. context.drawImage(img, 0, 0);
  32919. // Create VertexData from map data
  32920. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32921. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32922. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32923. //execute success callback, if set
  32924. if (onSuccess) {
  32925. onSuccess(_this);
  32926. }
  32927. };
  32928. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32929. return this;
  32930. };
  32931. /**
  32932. * Modifies the mesh geometry according to a displacementMap buffer.
  32933. * 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.
  32934. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32935. * This method returns nothing.
  32936. * 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.
  32937. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32938. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32939. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32940. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32941. *
  32942. * Returns the Mesh.
  32943. */
  32944. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32945. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32946. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32947. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32948. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32949. return this;
  32950. }
  32951. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32952. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32953. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32954. var position = BABYLON.Vector3.Zero();
  32955. var normal = BABYLON.Vector3.Zero();
  32956. var uv = BABYLON.Vector2.Zero();
  32957. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32958. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32959. for (var index = 0; index < positions.length; index += 3) {
  32960. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32961. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32962. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32963. // Compute height
  32964. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32965. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32966. var pos = (u + v * heightMapWidth) * 4;
  32967. var r = buffer[pos] / 255.0;
  32968. var g = buffer[pos + 1] / 255.0;
  32969. var b = buffer[pos + 2] / 255.0;
  32970. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32971. normal.normalize();
  32972. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32973. position = position.add(normal);
  32974. position.toArray(positions, index);
  32975. }
  32976. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32977. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32978. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32979. return this;
  32980. };
  32981. /**
  32982. * Modify the mesh to get a flat shading rendering.
  32983. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32984. * This method returns the Mesh.
  32985. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32986. */
  32987. Mesh.prototype.convertToFlatShadedMesh = function () {
  32988. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32989. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32990. var kinds = this.getVerticesDataKinds();
  32991. var vbs = {};
  32992. var data = {};
  32993. var newdata = {};
  32994. var updatableNormals = false;
  32995. var kindIndex;
  32996. var kind;
  32997. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32998. kind = kinds[kindIndex];
  32999. var vertexBuffer = this.getVertexBuffer(kind);
  33000. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33001. updatableNormals = vertexBuffer.isUpdatable();
  33002. kinds.splice(kindIndex, 1);
  33003. kindIndex--;
  33004. continue;
  33005. }
  33006. vbs[kind] = vertexBuffer;
  33007. data[kind] = vbs[kind].getData();
  33008. newdata[kind] = [];
  33009. }
  33010. // Save previous submeshes
  33011. var previousSubmeshes = this.subMeshes.slice(0);
  33012. var indices = this.getIndices();
  33013. var totalIndices = this.getTotalIndices();
  33014. // Generating unique vertices per face
  33015. var index;
  33016. for (index = 0; index < totalIndices; index++) {
  33017. var vertexIndex = indices[index];
  33018. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33019. kind = kinds[kindIndex];
  33020. var stride = vbs[kind].getStrideSize();
  33021. for (var offset = 0; offset < stride; offset++) {
  33022. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33023. }
  33024. }
  33025. }
  33026. // Updating faces & normal
  33027. var normals = [];
  33028. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33029. for (index = 0; index < totalIndices; index += 3) {
  33030. indices[index] = index;
  33031. indices[index + 1] = index + 1;
  33032. indices[index + 2] = index + 2;
  33033. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33034. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33035. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33036. var p1p2 = p1.subtract(p2);
  33037. var p3p2 = p3.subtract(p2);
  33038. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33039. // Store same normals for every vertex
  33040. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33041. normals.push(normal.x);
  33042. normals.push(normal.y);
  33043. normals.push(normal.z);
  33044. }
  33045. }
  33046. this.setIndices(indices);
  33047. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33048. // Updating vertex buffers
  33049. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33050. kind = kinds[kindIndex];
  33051. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33052. }
  33053. // Updating submeshes
  33054. this.releaseSubMeshes();
  33055. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33056. var previousOne = previousSubmeshes[submeshIndex];
  33057. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33058. }
  33059. this.synchronizeInstances();
  33060. return this;
  33061. };
  33062. /**
  33063. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33064. * In other words, more vertices, no more indices and a single bigger VBO.
  33065. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33066. * Returns the Mesh.
  33067. */
  33068. Mesh.prototype.convertToUnIndexedMesh = function () {
  33069. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33070. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33071. var kinds = this.getVerticesDataKinds();
  33072. var vbs = {};
  33073. var data = {};
  33074. var newdata = {};
  33075. var kindIndex;
  33076. var kind;
  33077. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33078. kind = kinds[kindIndex];
  33079. var vertexBuffer = this.getVertexBuffer(kind);
  33080. vbs[kind] = vertexBuffer;
  33081. data[kind] = vbs[kind].getData();
  33082. newdata[kind] = [];
  33083. }
  33084. // Save previous submeshes
  33085. var previousSubmeshes = this.subMeshes.slice(0);
  33086. var indices = this.getIndices();
  33087. var totalIndices = this.getTotalIndices();
  33088. // Generating unique vertices per face
  33089. var index;
  33090. for (index = 0; index < totalIndices; index++) {
  33091. var vertexIndex = indices[index];
  33092. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33093. kind = kinds[kindIndex];
  33094. var stride = vbs[kind].getStrideSize();
  33095. for (var offset = 0; offset < stride; offset++) {
  33096. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33097. }
  33098. }
  33099. }
  33100. // Updating indices
  33101. for (index = 0; index < totalIndices; index += 3) {
  33102. indices[index] = index;
  33103. indices[index + 1] = index + 1;
  33104. indices[index + 2] = index + 2;
  33105. }
  33106. this.setIndices(indices);
  33107. // Updating vertex buffers
  33108. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33109. kind = kinds[kindIndex];
  33110. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33111. }
  33112. // Updating submeshes
  33113. this.releaseSubMeshes();
  33114. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33115. var previousOne = previousSubmeshes[submeshIndex];
  33116. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33117. }
  33118. this._unIndexed = true;
  33119. this.synchronizeInstances();
  33120. return this;
  33121. };
  33122. /**
  33123. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33124. * This method returns the Mesh.
  33125. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33126. */
  33127. Mesh.prototype.flipFaces = function (flipNormals) {
  33128. if (flipNormals === void 0) { flipNormals = false; }
  33129. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33130. var i;
  33131. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33132. for (i = 0; i < vertex_data.normals.length; i++) {
  33133. vertex_data.normals[i] *= -1;
  33134. }
  33135. }
  33136. if (vertex_data.indices) {
  33137. var temp;
  33138. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33139. // reassign indices
  33140. temp = vertex_data.indices[i + 1];
  33141. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33142. vertex_data.indices[i + 2] = temp;
  33143. }
  33144. }
  33145. vertex_data.applyToMesh(this);
  33146. return this;
  33147. };
  33148. // Instances
  33149. /**
  33150. * Creates a new InstancedMesh object from the mesh model.
  33151. * An instance shares the same properties and the same material than its model.
  33152. * Only these properties of each instance can then be set individually :
  33153. * - position
  33154. * - rotation
  33155. * - rotationQuaternion
  33156. * - setPivotMatrix
  33157. * - scaling
  33158. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33159. * Warning : this method is not supported for Line mesh and LineSystem
  33160. */
  33161. Mesh.prototype.createInstance = function (name) {
  33162. return new BABYLON.InstancedMesh(name, this);
  33163. };
  33164. /**
  33165. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33166. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33167. * This method returns the Mesh.
  33168. */
  33169. Mesh.prototype.synchronizeInstances = function () {
  33170. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33171. var instance = this.instances[instanceIndex];
  33172. instance._syncSubMeshes();
  33173. }
  33174. return this;
  33175. };
  33176. /**
  33177. * Simplify the mesh according to the given array of settings.
  33178. * Function will return immediately and will simplify async. It returns the Mesh.
  33179. * @param settings a collection of simplification settings.
  33180. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33181. * @param type the type of simplification to run.
  33182. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33183. */
  33184. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33185. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33186. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33187. this.getScene().simplificationQueue.addTask({
  33188. settings: settings,
  33189. parallelProcessing: parallelProcessing,
  33190. mesh: this,
  33191. simplificationType: simplificationType,
  33192. successCallback: successCallback
  33193. });
  33194. return this;
  33195. };
  33196. /**
  33197. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33198. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33199. * This should be used together with the simplification to avoid disappearing triangles.
  33200. * Returns the Mesh.
  33201. * @param successCallback an optional success callback to be called after the optimization finished.
  33202. */
  33203. Mesh.prototype.optimizeIndices = function (successCallback) {
  33204. var _this = this;
  33205. var indices = this.getIndices();
  33206. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33207. if (!positions || !indices) {
  33208. return this;
  33209. }
  33210. var vectorPositions = new Array();
  33211. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33212. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33213. }
  33214. var dupes = new Array();
  33215. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33216. var realPos = vectorPositions.length - 1 - iteration;
  33217. var testedPosition = vectorPositions[realPos];
  33218. for (var j = 0; j < realPos; ++j) {
  33219. var againstPosition = vectorPositions[j];
  33220. if (testedPosition.equals(againstPosition)) {
  33221. dupes[realPos] = j;
  33222. break;
  33223. }
  33224. }
  33225. }, function () {
  33226. for (var i = 0; i < indices.length; ++i) {
  33227. indices[i] = dupes[indices[i]] || indices[i];
  33228. }
  33229. //indices are now reordered
  33230. var originalSubMeshes = _this.subMeshes.slice(0);
  33231. _this.setIndices(indices);
  33232. _this.subMeshes = originalSubMeshes;
  33233. if (successCallback) {
  33234. successCallback(_this);
  33235. }
  33236. });
  33237. return this;
  33238. };
  33239. Mesh.prototype.serialize = function (serializationObject) {
  33240. serializationObject.name = this.name;
  33241. serializationObject.id = this.id;
  33242. serializationObject.type = this.getClassName();
  33243. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33244. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33245. }
  33246. serializationObject.position = this.position.asArray();
  33247. if (this.rotationQuaternion) {
  33248. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33249. }
  33250. else if (this.rotation) {
  33251. serializationObject.rotation = this.rotation.asArray();
  33252. }
  33253. serializationObject.scaling = this.scaling.asArray();
  33254. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33255. serializationObject.isEnabled = this.isEnabled(false);
  33256. serializationObject.isVisible = this.isVisible;
  33257. serializationObject.infiniteDistance = this.infiniteDistance;
  33258. serializationObject.pickable = this.isPickable;
  33259. serializationObject.receiveShadows = this.receiveShadows;
  33260. serializationObject.billboardMode = this.billboardMode;
  33261. serializationObject.visibility = this.visibility;
  33262. serializationObject.checkCollisions = this.checkCollisions;
  33263. serializationObject.isBlocker = this.isBlocker;
  33264. // Parent
  33265. if (this.parent) {
  33266. serializationObject.parentId = this.parent.id;
  33267. }
  33268. // Geometry
  33269. serializationObject.isUnIndexed = this.isUnIndexed;
  33270. var geometry = this._geometry;
  33271. if (geometry) {
  33272. var geometryId = geometry.id;
  33273. serializationObject.geometryId = geometryId;
  33274. // SubMeshes
  33275. serializationObject.subMeshes = [];
  33276. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33277. var subMesh = this.subMeshes[subIndex];
  33278. serializationObject.subMeshes.push({
  33279. materialIndex: subMesh.materialIndex,
  33280. verticesStart: subMesh.verticesStart,
  33281. verticesCount: subMesh.verticesCount,
  33282. indexStart: subMesh.indexStart,
  33283. indexCount: subMesh.indexCount
  33284. });
  33285. }
  33286. }
  33287. // Material
  33288. if (this.material) {
  33289. serializationObject.materialId = this.material.id;
  33290. }
  33291. else {
  33292. this.material = null;
  33293. }
  33294. // Morph targets
  33295. if (this.morphTargetManager) {
  33296. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33297. }
  33298. // Skeleton
  33299. if (this.skeleton) {
  33300. serializationObject.skeletonId = this.skeleton.id;
  33301. }
  33302. // Physics
  33303. //TODO implement correct serialization for physics impostors.
  33304. var impostor = this.getPhysicsImpostor();
  33305. if (impostor) {
  33306. serializationObject.physicsMass = impostor.getParam("mass");
  33307. serializationObject.physicsFriction = impostor.getParam("friction");
  33308. serializationObject.physicsRestitution = impostor.getParam("mass");
  33309. serializationObject.physicsImpostor = impostor.type;
  33310. }
  33311. // Metadata
  33312. if (this.metadata) {
  33313. serializationObject.metadata = this.metadata;
  33314. }
  33315. // Instances
  33316. serializationObject.instances = [];
  33317. for (var index = 0; index < this.instances.length; index++) {
  33318. var instance = this.instances[index];
  33319. var serializationInstance = {
  33320. name: instance.name,
  33321. id: instance.id,
  33322. position: instance.position.asArray(),
  33323. scaling: instance.scaling.asArray()
  33324. };
  33325. if (instance.rotationQuaternion) {
  33326. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33327. }
  33328. else if (instance.rotation) {
  33329. serializationInstance.rotation = instance.rotation.asArray();
  33330. }
  33331. serializationObject.instances.push(serializationInstance);
  33332. // Animations
  33333. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33334. serializationInstance.ranges = instance.serializeAnimationRanges();
  33335. }
  33336. //
  33337. // Animations
  33338. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33339. serializationObject.ranges = this.serializeAnimationRanges();
  33340. // Layer mask
  33341. serializationObject.layerMask = this.layerMask;
  33342. // Alpha
  33343. serializationObject.alphaIndex = this.alphaIndex;
  33344. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33345. // Overlay
  33346. serializationObject.overlayAlpha = this.overlayAlpha;
  33347. serializationObject.overlayColor = this.overlayColor.asArray();
  33348. serializationObject.renderOverlay = this.renderOverlay;
  33349. // Fog
  33350. serializationObject.applyFog = this.applyFog;
  33351. // Action Manager
  33352. if (this.actionManager) {
  33353. serializationObject.actions = this.actionManager.serialize(this.name);
  33354. }
  33355. };
  33356. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33357. if (!this.geometry) {
  33358. return;
  33359. }
  33360. this._markSubMeshesAsAttributesDirty();
  33361. var morphTargetManager = this._morphTargetManager;
  33362. if (morphTargetManager && morphTargetManager.vertexCount) {
  33363. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33364. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33365. this.morphTargetManager = null;
  33366. return;
  33367. }
  33368. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33369. var morphTarget = morphTargetManager.getActiveTarget(index);
  33370. var positions = morphTarget.getPositions();
  33371. if (!positions) {
  33372. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33373. return;
  33374. }
  33375. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33376. var normals = morphTarget.getNormals();
  33377. if (normals) {
  33378. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33379. }
  33380. var tangents = morphTarget.getTangents();
  33381. if (tangents) {
  33382. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33383. }
  33384. }
  33385. }
  33386. else {
  33387. var index = 0;
  33388. // Positions
  33389. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33390. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33391. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33392. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33393. }
  33394. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33395. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33396. }
  33397. index++;
  33398. }
  33399. }
  33400. };
  33401. // Statics
  33402. /**
  33403. * Returns a new Mesh object parsed from the source provided.
  33404. * The parameter `parsedMesh` is the source.
  33405. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33406. */
  33407. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33408. var mesh;
  33409. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33410. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33411. }
  33412. else {
  33413. mesh = new Mesh(parsedMesh.name, scene);
  33414. }
  33415. mesh.id = parsedMesh.id;
  33416. if (BABYLON.Tags) {
  33417. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33418. }
  33419. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33420. if (parsedMesh.metadata !== undefined) {
  33421. mesh.metadata = parsedMesh.metadata;
  33422. }
  33423. if (parsedMesh.rotationQuaternion) {
  33424. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33425. }
  33426. else if (parsedMesh.rotation) {
  33427. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33428. }
  33429. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33430. if (parsedMesh.localMatrix) {
  33431. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33432. }
  33433. else if (parsedMesh.pivotMatrix) {
  33434. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33435. }
  33436. mesh.setEnabled(parsedMesh.isEnabled);
  33437. mesh.isVisible = parsedMesh.isVisible;
  33438. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33439. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33440. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33441. if (parsedMesh.applyFog !== undefined) {
  33442. mesh.applyFog = parsedMesh.applyFog;
  33443. }
  33444. if (parsedMesh.pickable !== undefined) {
  33445. mesh.isPickable = parsedMesh.pickable;
  33446. }
  33447. if (parsedMesh.alphaIndex !== undefined) {
  33448. mesh.alphaIndex = parsedMesh.alphaIndex;
  33449. }
  33450. mesh.receiveShadows = parsedMesh.receiveShadows;
  33451. mesh.billboardMode = parsedMesh.billboardMode;
  33452. if (parsedMesh.visibility !== undefined) {
  33453. mesh.visibility = parsedMesh.visibility;
  33454. }
  33455. mesh.checkCollisions = parsedMesh.checkCollisions;
  33456. if (parsedMesh.isBlocker !== undefined) {
  33457. mesh.isBlocker = parsedMesh.isBlocker;
  33458. }
  33459. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33460. // freezeWorldMatrix
  33461. if (parsedMesh.freezeWorldMatrix) {
  33462. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33463. }
  33464. // Parent
  33465. if (parsedMesh.parentId) {
  33466. mesh._waitingParentId = parsedMesh.parentId;
  33467. }
  33468. // Actions
  33469. if (parsedMesh.actions !== undefined) {
  33470. mesh._waitingActions = parsedMesh.actions;
  33471. }
  33472. // Overlay
  33473. if (parsedMesh.overlayAlpha !== undefined) {
  33474. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33475. }
  33476. if (parsedMesh.overlayColor !== undefined) {
  33477. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33478. }
  33479. if (parsedMesh.renderOverlay !== undefined) {
  33480. mesh.renderOverlay = parsedMesh.renderOverlay;
  33481. }
  33482. // Geometry
  33483. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33484. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33485. if (parsedMesh.delayLoadingFile) {
  33486. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33487. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33488. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33489. if (parsedMesh._binaryInfo) {
  33490. mesh._binaryInfo = parsedMesh._binaryInfo;
  33491. }
  33492. mesh._delayInfo = [];
  33493. if (parsedMesh.hasUVs) {
  33494. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33495. }
  33496. if (parsedMesh.hasUVs2) {
  33497. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33498. }
  33499. if (parsedMesh.hasUVs3) {
  33500. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33501. }
  33502. if (parsedMesh.hasUVs4) {
  33503. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33504. }
  33505. if (parsedMesh.hasUVs5) {
  33506. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33507. }
  33508. if (parsedMesh.hasUVs6) {
  33509. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33510. }
  33511. if (parsedMesh.hasColors) {
  33512. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33513. }
  33514. if (parsedMesh.hasMatricesIndices) {
  33515. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33516. }
  33517. if (parsedMesh.hasMatricesWeights) {
  33518. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33519. }
  33520. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33521. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33522. mesh._checkDelayState();
  33523. }
  33524. }
  33525. else {
  33526. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33527. }
  33528. // Material
  33529. if (parsedMesh.materialId) {
  33530. mesh.setMaterialByID(parsedMesh.materialId);
  33531. }
  33532. else {
  33533. mesh.material = null;
  33534. }
  33535. // Morph targets
  33536. if (parsedMesh.morphTargetManagerId > -1) {
  33537. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33538. }
  33539. // Skeleton
  33540. if (parsedMesh.skeletonId > -1) {
  33541. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33542. if (parsedMesh.numBoneInfluencers) {
  33543. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33544. }
  33545. }
  33546. // Animations
  33547. if (parsedMesh.animations) {
  33548. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33549. var parsedAnimation = parsedMesh.animations[animationIndex];
  33550. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33551. }
  33552. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33553. }
  33554. if (parsedMesh.autoAnimate) {
  33555. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33556. }
  33557. // Layer Mask
  33558. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33559. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33560. }
  33561. else {
  33562. mesh.layerMask = 0x0FFFFFFF;
  33563. }
  33564. // Physics
  33565. if (parsedMesh.physicsImpostor) {
  33566. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33567. mass: parsedMesh.physicsMass,
  33568. friction: parsedMesh.physicsFriction,
  33569. restitution: parsedMesh.physicsRestitution
  33570. }, scene);
  33571. }
  33572. // Instances
  33573. if (parsedMesh.instances) {
  33574. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33575. var parsedInstance = parsedMesh.instances[index];
  33576. var instance = mesh.createInstance(parsedInstance.name);
  33577. if (parsedInstance.id) {
  33578. instance.id = parsedInstance.id;
  33579. }
  33580. if (BABYLON.Tags) {
  33581. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33582. }
  33583. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33584. if (parsedInstance.parentId) {
  33585. instance._waitingParentId = parsedInstance.parentId;
  33586. }
  33587. if (parsedInstance.rotationQuaternion) {
  33588. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33589. }
  33590. else if (parsedInstance.rotation) {
  33591. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33592. }
  33593. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33594. instance.checkCollisions = mesh.checkCollisions;
  33595. if (parsedMesh.animations) {
  33596. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33597. parsedAnimation = parsedMesh.animations[animationIndex];
  33598. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33599. }
  33600. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33601. }
  33602. }
  33603. }
  33604. return mesh;
  33605. };
  33606. /**
  33607. * Creates a ribbon mesh.
  33608. * Please consider using the same method from the MeshBuilder class instead.
  33609. * 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.
  33610. *
  33611. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33612. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33613. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33614. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33615. * 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.
  33616. * 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.
  33617. * 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
  33618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33619. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33621. */
  33622. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33623. if (closeArray === void 0) { closeArray = false; }
  33624. if (updatable === void 0) { updatable = false; }
  33625. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33626. pathArray: pathArray,
  33627. closeArray: closeArray,
  33628. closePath: closePath,
  33629. offset: offset,
  33630. updatable: updatable,
  33631. sideOrientation: sideOrientation,
  33632. instance: instance
  33633. }, scene);
  33634. };
  33635. /**
  33636. * Creates a plane polygonal mesh. By default, this is a disc.
  33637. * Please consider using the same method from the MeshBuilder class instead.
  33638. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33639. * 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.
  33640. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33641. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33643. */
  33644. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33645. if (scene === void 0) { scene = null; }
  33646. var options = {
  33647. radius: radius,
  33648. tessellation: tessellation,
  33649. sideOrientation: sideOrientation,
  33650. updatable: updatable
  33651. };
  33652. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33653. };
  33654. /**
  33655. * Creates a box mesh.
  33656. * Please consider using the same method from the MeshBuilder class instead.
  33657. * The parameter `size` sets the size (float) of each box side (default 1).
  33658. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33659. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33660. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33661. */
  33662. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33663. if (scene === void 0) { scene = null; }
  33664. var options = {
  33665. size: size,
  33666. sideOrientation: sideOrientation,
  33667. updatable: updatable
  33668. };
  33669. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33670. };
  33671. /**
  33672. * Creates a sphere mesh.
  33673. * Please consider using the same method from the MeshBuilder class instead.
  33674. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33675. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33677. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33679. */
  33680. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33681. var options = {
  33682. segments: segments,
  33683. diameterX: diameter,
  33684. diameterY: diameter,
  33685. diameterZ: diameter,
  33686. sideOrientation: sideOrientation,
  33687. updatable: updatable
  33688. };
  33689. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33690. };
  33691. /**
  33692. * Creates a cylinder or a cone mesh.
  33693. * Please consider using the same method from the MeshBuilder class instead.
  33694. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33695. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33696. * 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.
  33697. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33698. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33699. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33700. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33702. */
  33703. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33704. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33705. if (scene !== undefined) {
  33706. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33707. updatable = scene;
  33708. }
  33709. scene = subdivisions;
  33710. subdivisions = 1;
  33711. }
  33712. var options = {
  33713. height: height,
  33714. diameterTop: diameterTop,
  33715. diameterBottom: diameterBottom,
  33716. tessellation: tessellation,
  33717. subdivisions: subdivisions,
  33718. sideOrientation: sideOrientation,
  33719. updatable: updatable
  33720. };
  33721. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33722. };
  33723. // Torus (Code from SharpDX.org)
  33724. /**
  33725. * Creates a torus mesh.
  33726. * Please consider using the same method from the MeshBuilder class instead.
  33727. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33728. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33729. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33731. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33733. */
  33734. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33735. var options = {
  33736. diameter: diameter,
  33737. thickness: thickness,
  33738. tessellation: tessellation,
  33739. sideOrientation: sideOrientation,
  33740. updatable: updatable
  33741. };
  33742. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33743. };
  33744. /**
  33745. * Creates a torus knot mesh.
  33746. * Please consider using the same method from the MeshBuilder class instead.
  33747. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33748. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33749. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33750. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33751. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33752. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33754. */
  33755. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33756. var options = {
  33757. radius: radius,
  33758. tube: tube,
  33759. radialSegments: radialSegments,
  33760. tubularSegments: tubularSegments,
  33761. p: p,
  33762. q: q,
  33763. sideOrientation: sideOrientation,
  33764. updatable: updatable
  33765. };
  33766. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33767. };
  33768. /**
  33769. * Creates a line mesh.
  33770. * Please consider using the same method from the MeshBuilder class instead.
  33771. * 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.
  33772. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33773. * The parameter `points` is an array successive Vector3.
  33774. * 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
  33775. * When updating an instance, remember that only point positions can change, not the number of points.
  33776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33777. */
  33778. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33779. if (scene === void 0) { scene = null; }
  33780. if (updatable === void 0) { updatable = false; }
  33781. if (instance === void 0) { instance = null; }
  33782. var options = {
  33783. points: points,
  33784. updatable: updatable,
  33785. instance: instance
  33786. };
  33787. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33788. };
  33789. /**
  33790. * Creates a dashed line mesh.
  33791. * Please consider using the same method from the MeshBuilder class instead.
  33792. * 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.
  33793. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33794. * The parameter `points` is an array successive Vector3.
  33795. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33796. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33797. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33798. * 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
  33799. * When updating an instance, remember that only point positions can change, not the number of points.
  33800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33801. */
  33802. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33803. if (scene === void 0) { scene = null; }
  33804. var options = {
  33805. points: points,
  33806. dashSize: dashSize,
  33807. gapSize: gapSize,
  33808. dashNb: dashNb,
  33809. updatable: updatable,
  33810. instance: instance
  33811. };
  33812. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33813. };
  33814. /**
  33815. * Creates a polygon mesh.
  33816. * Please consider using the same method from the MeshBuilder class instead.
  33817. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33818. * 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.
  33819. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33821. * Remember you can only change the shape positions, not their number when updating a polygon.
  33822. */
  33823. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33824. var options = {
  33825. shape: shape,
  33826. holes: holes,
  33827. updatable: updatable,
  33828. sideOrientation: sideOrientation
  33829. };
  33830. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33831. };
  33832. /**
  33833. * Creates an extruded polygon mesh, with depth in the Y direction.
  33834. * Please consider using the same method from the MeshBuilder class instead.
  33835. */
  33836. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33837. var options = {
  33838. shape: shape,
  33839. holes: holes,
  33840. depth: depth,
  33841. updatable: updatable,
  33842. sideOrientation: sideOrientation
  33843. };
  33844. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33845. };
  33846. /**
  33847. * Creates an extruded shape mesh.
  33848. * 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.
  33849. * Please consider using the same method from the MeshBuilder class instead.
  33850. *
  33851. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33852. * 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
  33853. * extruded along the Z axis.
  33854. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33855. * 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.
  33856. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33857. * 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
  33858. * 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
  33859. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33861. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33863. */
  33864. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33865. if (scene === void 0) { scene = null; }
  33866. var options = {
  33867. shape: shape,
  33868. path: path,
  33869. scale: scale,
  33870. rotation: rotation,
  33871. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33872. sideOrientation: sideOrientation,
  33873. instance: instance,
  33874. updatable: updatable
  33875. };
  33876. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33877. };
  33878. /**
  33879. * Creates an custom extruded shape mesh.
  33880. * 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.
  33881. * Please consider using the same method from the MeshBuilder class instead.
  33882. *
  33883. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33884. * 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
  33885. * extruded along the Z axis.
  33886. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33887. * 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
  33888. * and the distance of this point from the begining of the path :
  33889. * ```javascript
  33890. * var rotationFunction = function(i, distance) {
  33891. * // do things
  33892. * return rotationValue; }
  33893. * ```
  33894. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33895. * 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
  33896. * and the distance of this point from the begining of the path :
  33897. * ```javascript
  33898. * var scaleFunction = function(i, distance) {
  33899. * // do things
  33900. * return scaleValue;}
  33901. * ```
  33902. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33903. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33904. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33905. * 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
  33906. * 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
  33907. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33908. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33909. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33911. */
  33912. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33913. var options = {
  33914. shape: shape,
  33915. path: path,
  33916. scaleFunction: scaleFunction,
  33917. rotationFunction: rotationFunction,
  33918. ribbonCloseArray: ribbonCloseArray,
  33919. ribbonClosePath: ribbonClosePath,
  33920. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33921. sideOrientation: sideOrientation,
  33922. instance: instance,
  33923. updatable: updatable
  33924. };
  33925. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33926. };
  33927. /**
  33928. * Creates lathe mesh.
  33929. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33930. * Please consider using the same method from the MeshBuilder class instead.
  33931. * 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
  33932. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33933. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33934. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33936. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33938. */
  33939. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33940. var options = {
  33941. shape: shape,
  33942. radius: radius,
  33943. tessellation: tessellation,
  33944. sideOrientation: sideOrientation,
  33945. updatable: updatable
  33946. };
  33947. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33948. };
  33949. /**
  33950. * Creates a plane mesh.
  33951. * Please consider using the same method from the MeshBuilder class instead.
  33952. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33954. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33956. */
  33957. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33958. var options = {
  33959. size: size,
  33960. width: size,
  33961. height: size,
  33962. sideOrientation: sideOrientation,
  33963. updatable: updatable
  33964. };
  33965. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33966. };
  33967. /**
  33968. * Creates a ground mesh.
  33969. * Please consider using the same method from the MeshBuilder class instead.
  33970. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33971. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33973. */
  33974. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33975. var options = {
  33976. width: width,
  33977. height: height,
  33978. subdivisions: subdivisions,
  33979. updatable: updatable
  33980. };
  33981. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33982. };
  33983. /**
  33984. * Creates a tiled ground mesh.
  33985. * Please consider using the same method from the MeshBuilder class instead.
  33986. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33987. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33988. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33989. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33990. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33991. * numbers of subdivisions on the ground width and height of each tile.
  33992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33993. */
  33994. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33995. var options = {
  33996. xmin: xmin,
  33997. zmin: zmin,
  33998. xmax: xmax,
  33999. zmax: zmax,
  34000. subdivisions: subdivisions,
  34001. precision: precision,
  34002. updatable: updatable
  34003. };
  34004. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34005. };
  34006. /**
  34007. * Creates a ground mesh from a height map.
  34008. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34009. * Please consider using the same method from the MeshBuilder class instead.
  34010. * The parameter `url` sets the URL of the height map image resource.
  34011. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34012. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34013. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34014. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34015. * 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).
  34016. * This function is passed the newly built mesh :
  34017. * ```javascript
  34018. * function(mesh) { // do things
  34019. * return; }
  34020. * ```
  34021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34022. */
  34023. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34024. var options = {
  34025. width: width,
  34026. height: height,
  34027. subdivisions: subdivisions,
  34028. minHeight: minHeight,
  34029. maxHeight: maxHeight,
  34030. updatable: updatable,
  34031. onReady: onReady
  34032. };
  34033. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34034. };
  34035. /**
  34036. * Creates a tube mesh.
  34037. * 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.
  34038. * Please consider using the same method from the MeshBuilder class instead.
  34039. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34040. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34041. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34042. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34043. * 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.
  34044. * It must return a radius value (positive float) :
  34045. * ```javascript
  34046. * var radiusFunction = function(i, distance) {
  34047. * // do things
  34048. * return radius; }
  34049. * ```
  34050. * 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
  34051. * 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
  34052. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34053. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34055. */
  34056. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34057. var options = {
  34058. path: path,
  34059. radius: radius,
  34060. tessellation: tessellation,
  34061. radiusFunction: radiusFunction,
  34062. arc: 1,
  34063. cap: cap,
  34064. updatable: updatable,
  34065. sideOrientation: sideOrientation,
  34066. instance: instance
  34067. };
  34068. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34069. };
  34070. /**
  34071. * Creates a polyhedron mesh.
  34072. * Please consider using the same method from the MeshBuilder class instead.
  34073. * 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
  34074. * to choose the wanted type.
  34075. * The parameter `size` (positive float, default 1) sets the polygon size.
  34076. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34077. * 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`.
  34078. * 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
  34079. * 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)`).
  34080. * 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
  34081. * 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.
  34082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34083. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34085. */
  34086. Mesh.CreatePolyhedron = function (name, options, scene) {
  34087. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34088. };
  34089. /**
  34090. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34091. * Please consider using the same method from the MeshBuilder class instead.
  34092. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34093. * 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`).
  34094. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34095. * 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.
  34096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34097. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34099. */
  34100. Mesh.CreateIcoSphere = function (name, options, scene) {
  34101. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34102. };
  34103. /**
  34104. * Creates a decal mesh.
  34105. * Please consider using the same method from the MeshBuilder class instead.
  34106. * 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.
  34107. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34108. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34109. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34110. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34111. */
  34112. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34113. var options = {
  34114. position: position,
  34115. normal: normal,
  34116. size: size,
  34117. angle: angle
  34118. };
  34119. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34120. };
  34121. // Skeletons
  34122. /**
  34123. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34124. */
  34125. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34126. if (!this._sourcePositions) {
  34127. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34128. if (!source) {
  34129. return this._sourcePositions;
  34130. }
  34131. this._sourcePositions = new Float32Array(source);
  34132. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34133. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34134. }
  34135. }
  34136. return this._sourcePositions;
  34137. };
  34138. /**
  34139. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34140. */
  34141. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34142. if (!this._sourceNormals) {
  34143. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34144. if (!source) {
  34145. return this._sourceNormals;
  34146. }
  34147. this._sourceNormals = new Float32Array(source);
  34148. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34149. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34150. }
  34151. }
  34152. return this._sourceNormals;
  34153. };
  34154. /**
  34155. * Updates the vertex buffer by applying transformation from the bones.
  34156. * Returns the Mesh.
  34157. *
  34158. * @param {skeleton} skeleton to apply
  34159. */
  34160. Mesh.prototype.applySkeleton = function (skeleton) {
  34161. if (!this.geometry) {
  34162. return this;
  34163. }
  34164. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34165. return this;
  34166. }
  34167. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34168. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34169. return this;
  34170. }
  34171. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34172. return this;
  34173. }
  34174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34175. return this;
  34176. }
  34177. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34178. return this;
  34179. }
  34180. if (!this._sourcePositions) {
  34181. var submeshes = this.subMeshes.slice();
  34182. this.setPositionsForCPUSkinning();
  34183. this.subMeshes = submeshes;
  34184. }
  34185. if (!this._sourceNormals) {
  34186. this.setNormalsForCPUSkinning();
  34187. }
  34188. // positionsData checks for not being Float32Array will only pass at most once
  34189. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34190. if (!positionsData) {
  34191. return this;
  34192. }
  34193. if (!(positionsData instanceof Float32Array)) {
  34194. positionsData = new Float32Array(positionsData);
  34195. }
  34196. // normalsData checks for not being Float32Array will only pass at most once
  34197. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34198. if (!normalsData) {
  34199. return this;
  34200. }
  34201. if (!(normalsData instanceof Float32Array)) {
  34202. normalsData = new Float32Array(normalsData);
  34203. }
  34204. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34205. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34206. if (!matricesWeightsData || !matricesIndicesData) {
  34207. return this;
  34208. }
  34209. var needExtras = this.numBoneInfluencers > 4;
  34210. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34211. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34212. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34213. var tempVector3 = BABYLON.Vector3.Zero();
  34214. var finalMatrix = new BABYLON.Matrix();
  34215. var tempMatrix = new BABYLON.Matrix();
  34216. var matWeightIdx = 0;
  34217. var inf;
  34218. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34219. var weight;
  34220. for (inf = 0; inf < 4; inf++) {
  34221. weight = matricesWeightsData[matWeightIdx + inf];
  34222. if (weight > 0) {
  34223. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34224. finalMatrix.addToSelf(tempMatrix);
  34225. }
  34226. else
  34227. break;
  34228. }
  34229. if (needExtras) {
  34230. for (inf = 0; inf < 4; inf++) {
  34231. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34232. if (weight > 0) {
  34233. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34234. finalMatrix.addToSelf(tempMatrix);
  34235. }
  34236. else
  34237. break;
  34238. }
  34239. }
  34240. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34241. tempVector3.toArray(positionsData, index);
  34242. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34243. tempVector3.toArray(normalsData, index);
  34244. finalMatrix.reset();
  34245. }
  34246. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34247. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34248. return this;
  34249. };
  34250. // Tools
  34251. /**
  34252. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34253. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34254. */
  34255. Mesh.MinMax = function (meshes) {
  34256. var minVector = null;
  34257. var maxVector = null;
  34258. meshes.forEach(function (mesh, index, array) {
  34259. var boundingInfo = mesh.getBoundingInfo();
  34260. var boundingBox = boundingInfo.boundingBox;
  34261. if (!minVector || !maxVector) {
  34262. minVector = boundingBox.minimumWorld;
  34263. maxVector = boundingBox.maximumWorld;
  34264. }
  34265. else {
  34266. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34267. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34268. }
  34269. });
  34270. if (!minVector || !maxVector) {
  34271. return {
  34272. min: BABYLON.Vector3.Zero(),
  34273. max: BABYLON.Vector3.Zero()
  34274. };
  34275. }
  34276. return {
  34277. min: minVector,
  34278. max: maxVector
  34279. };
  34280. };
  34281. /**
  34282. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34283. */
  34284. Mesh.Center = function (meshesOrMinMaxVector) {
  34285. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34286. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34287. };
  34288. /**
  34289. * Merge the array of meshes into a single mesh for performance reasons.
  34290. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34291. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34292. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34293. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34294. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34295. */
  34296. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34297. if (disposeSource === void 0) { disposeSource = true; }
  34298. var index;
  34299. if (!allow32BitsIndices) {
  34300. var totalVertices = 0;
  34301. // Counting vertices
  34302. for (index = 0; index < meshes.length; index++) {
  34303. if (meshes[index]) {
  34304. totalVertices += meshes[index].getTotalVertices();
  34305. if (totalVertices > 65536) {
  34306. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34307. return null;
  34308. }
  34309. }
  34310. }
  34311. }
  34312. // Merge
  34313. var vertexData = null;
  34314. var otherVertexData;
  34315. var indiceArray = new Array();
  34316. var source = null;
  34317. for (index = 0; index < meshes.length; index++) {
  34318. if (meshes[index]) {
  34319. meshes[index].computeWorldMatrix(true);
  34320. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34321. otherVertexData.transform(meshes[index].getWorldMatrix());
  34322. if (vertexData) {
  34323. vertexData.merge(otherVertexData);
  34324. }
  34325. else {
  34326. vertexData = otherVertexData;
  34327. source = meshes[index];
  34328. }
  34329. if (subdivideWithSubMeshes) {
  34330. indiceArray.push(meshes[index].getTotalIndices());
  34331. }
  34332. }
  34333. }
  34334. source = source;
  34335. if (!meshSubclass) {
  34336. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34337. }
  34338. vertexData.applyToMesh(meshSubclass);
  34339. // Setting properties
  34340. meshSubclass.material = source.material;
  34341. meshSubclass.checkCollisions = source.checkCollisions;
  34342. // Cleaning
  34343. if (disposeSource) {
  34344. for (index = 0; index < meshes.length; index++) {
  34345. if (meshes[index]) {
  34346. meshes[index].dispose();
  34347. }
  34348. }
  34349. }
  34350. // Subdivide
  34351. if (subdivideWithSubMeshes) {
  34352. //-- removal of global submesh
  34353. meshSubclass.releaseSubMeshes();
  34354. index = 0;
  34355. var offset = 0;
  34356. //-- apply subdivision according to index table
  34357. while (index < indiceArray.length) {
  34358. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34359. offset += indiceArray[index];
  34360. index++;
  34361. }
  34362. }
  34363. return meshSubclass;
  34364. };
  34365. // Consts
  34366. Mesh._FRONTSIDE = 0;
  34367. Mesh._BACKSIDE = 1;
  34368. Mesh._DOUBLESIDE = 2;
  34369. Mesh._DEFAULTSIDE = 0;
  34370. Mesh._NO_CAP = 0;
  34371. Mesh._CAP_START = 1;
  34372. Mesh._CAP_END = 2;
  34373. Mesh._CAP_ALL = 3;
  34374. return Mesh;
  34375. }(BABYLON.AbstractMesh));
  34376. BABYLON.Mesh = Mesh;
  34377. })(BABYLON || (BABYLON = {}));
  34378. //# sourceMappingURL=babylon.mesh.js.map
  34379. var BABYLON;
  34380. (function (BABYLON) {
  34381. var BaseSubMesh = /** @class */ (function () {
  34382. function BaseSubMesh() {
  34383. }
  34384. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34385. get: function () {
  34386. return this._materialEffect;
  34387. },
  34388. enumerable: true,
  34389. configurable: true
  34390. });
  34391. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34392. if (defines === void 0) { defines = null; }
  34393. if (this._materialEffect === effect) {
  34394. if (!effect) {
  34395. this._materialDefines = null;
  34396. }
  34397. return;
  34398. }
  34399. this._materialDefines = defines;
  34400. this._materialEffect = effect;
  34401. };
  34402. return BaseSubMesh;
  34403. }());
  34404. BABYLON.BaseSubMesh = BaseSubMesh;
  34405. var SubMesh = /** @class */ (function (_super) {
  34406. __extends(SubMesh, _super);
  34407. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34408. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34409. var _this = _super.call(this) || this;
  34410. _this.materialIndex = materialIndex;
  34411. _this.verticesStart = verticesStart;
  34412. _this.verticesCount = verticesCount;
  34413. _this.indexStart = indexStart;
  34414. _this.indexCount = indexCount;
  34415. _this._renderId = 0;
  34416. _this._mesh = mesh;
  34417. _this._renderingMesh = renderingMesh || mesh;
  34418. mesh.subMeshes.push(_this);
  34419. _this._trianglePlanes = [];
  34420. _this._id = mesh.subMeshes.length - 1;
  34421. if (createBoundingBox) {
  34422. _this.refreshBoundingInfo();
  34423. mesh.computeWorldMatrix(true);
  34424. }
  34425. return _this;
  34426. }
  34427. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34428. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34429. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34430. };
  34431. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34432. get: function () {
  34433. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34434. },
  34435. enumerable: true,
  34436. configurable: true
  34437. });
  34438. /**
  34439. * Returns the submesh BoudingInfo object.
  34440. */
  34441. SubMesh.prototype.getBoundingInfo = function () {
  34442. if (this.IsGlobal) {
  34443. return this._mesh.getBoundingInfo();
  34444. }
  34445. return this._boundingInfo;
  34446. };
  34447. /**
  34448. * Sets the submesh BoundingInfo.
  34449. * Return the SubMesh.
  34450. */
  34451. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34452. this._boundingInfo = boundingInfo;
  34453. return this;
  34454. };
  34455. /**
  34456. * Returns the mesh of the current submesh.
  34457. */
  34458. SubMesh.prototype.getMesh = function () {
  34459. return this._mesh;
  34460. };
  34461. /**
  34462. * Returns the rendering mesh of the submesh.
  34463. */
  34464. SubMesh.prototype.getRenderingMesh = function () {
  34465. return this._renderingMesh;
  34466. };
  34467. /**
  34468. * Returns the submesh material.
  34469. */
  34470. SubMesh.prototype.getMaterial = function () {
  34471. var rootMaterial = this._renderingMesh.material;
  34472. if (rootMaterial === null || rootMaterial === undefined) {
  34473. return this._mesh.getScene().defaultMaterial;
  34474. }
  34475. else if (rootMaterial.getSubMaterial) {
  34476. var multiMaterial = rootMaterial;
  34477. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34478. if (this._currentMaterial !== effectiveMaterial) {
  34479. this._currentMaterial = effectiveMaterial;
  34480. this._materialDefines = null;
  34481. }
  34482. return effectiveMaterial;
  34483. }
  34484. return rootMaterial;
  34485. };
  34486. // Methods
  34487. /**
  34488. * Sets a new updated BoundingInfo object to the submesh.
  34489. * Returns the SubMesh.
  34490. */
  34491. SubMesh.prototype.refreshBoundingInfo = function () {
  34492. this._lastColliderWorldVertices = null;
  34493. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34494. return this;
  34495. }
  34496. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34497. if (!data) {
  34498. this._boundingInfo = this._mesh.getBoundingInfo();
  34499. return this;
  34500. }
  34501. var indices = this._renderingMesh.getIndices();
  34502. var extend;
  34503. //is this the only submesh?
  34504. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34505. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34506. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34507. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34508. }
  34509. else {
  34510. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34511. }
  34512. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34513. return this;
  34514. };
  34515. SubMesh.prototype._checkCollision = function (collider) {
  34516. var boundingInfo = this.getBoundingInfo();
  34517. return boundingInfo._checkCollision(collider);
  34518. };
  34519. /**
  34520. * Updates the submesh BoundingInfo.
  34521. * Returns the Submesh.
  34522. */
  34523. SubMesh.prototype.updateBoundingInfo = function (world) {
  34524. var boundingInfo = this.getBoundingInfo();
  34525. if (!boundingInfo) {
  34526. this.refreshBoundingInfo();
  34527. boundingInfo = this.getBoundingInfo();
  34528. }
  34529. boundingInfo.update(world);
  34530. return this;
  34531. };
  34532. /**
  34533. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34534. * Boolean returned.
  34535. */
  34536. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34537. var boundingInfo = this.getBoundingInfo();
  34538. if (!boundingInfo) {
  34539. return false;
  34540. }
  34541. return boundingInfo.isInFrustum(frustumPlanes);
  34542. };
  34543. /**
  34544. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34545. * Boolean returned.
  34546. */
  34547. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34548. var boundingInfo = this.getBoundingInfo();
  34549. if (!boundingInfo) {
  34550. return false;
  34551. }
  34552. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34553. };
  34554. /**
  34555. * Renders the submesh.
  34556. * Returns it.
  34557. */
  34558. SubMesh.prototype.render = function (enableAlphaMode) {
  34559. this._renderingMesh.render(this, enableAlphaMode);
  34560. return this;
  34561. };
  34562. /**
  34563. * Returns a new Index Buffer.
  34564. * Type returned : WebGLBuffer.
  34565. */
  34566. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34567. if (!this._linesIndexBuffer) {
  34568. var linesIndices = [];
  34569. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34570. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34571. }
  34572. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34573. this.linesIndexCount = linesIndices.length;
  34574. }
  34575. return this._linesIndexBuffer;
  34576. };
  34577. /**
  34578. * True is the passed Ray intersects the submesh bounding box.
  34579. * Boolean returned.
  34580. */
  34581. SubMesh.prototype.canIntersects = function (ray) {
  34582. var boundingInfo = this.getBoundingInfo();
  34583. if (!boundingInfo) {
  34584. return false;
  34585. }
  34586. return ray.intersectsBox(boundingInfo.boundingBox);
  34587. };
  34588. /**
  34589. * Returns an object IntersectionInfo.
  34590. */
  34591. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34592. var intersectInfo = null;
  34593. var material = this.getMaterial();
  34594. if (!material) {
  34595. return null;
  34596. }
  34597. switch (material.fillMode) {
  34598. case BABYLON.Material.PointListDrawMode:
  34599. case BABYLON.Material.LineListDrawMode:
  34600. case BABYLON.Material.LineLoopDrawMode:
  34601. case BABYLON.Material.LineStripDrawMode:
  34602. case BABYLON.Material.TriangleFanDrawMode:
  34603. case BABYLON.Material.TriangleStripDrawMode:
  34604. return null;
  34605. }
  34606. // LineMesh first as it's also a Mesh...
  34607. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34608. var lineMesh = this._mesh;
  34609. // Line test
  34610. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34611. var p0 = positions[indices[index]];
  34612. var p1 = positions[indices[index + 1]];
  34613. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34614. if (length < 0) {
  34615. continue;
  34616. }
  34617. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34618. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34619. if (fastCheck) {
  34620. break;
  34621. }
  34622. }
  34623. }
  34624. }
  34625. else {
  34626. // Triangles test
  34627. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34628. var p0 = positions[indices[index]];
  34629. var p1 = positions[indices[index + 1]];
  34630. var p2 = positions[indices[index + 2]];
  34631. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34632. if (currentIntersectInfo) {
  34633. if (currentIntersectInfo.distance < 0) {
  34634. continue;
  34635. }
  34636. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34637. intersectInfo = currentIntersectInfo;
  34638. intersectInfo.faceId = index / 3;
  34639. if (fastCheck) {
  34640. break;
  34641. }
  34642. }
  34643. }
  34644. }
  34645. }
  34646. return intersectInfo;
  34647. };
  34648. SubMesh.prototype._rebuild = function () {
  34649. if (this._linesIndexBuffer) {
  34650. this._linesIndexBuffer = null;
  34651. }
  34652. };
  34653. // Clone
  34654. /**
  34655. * Creates a new Submesh from the passed Mesh.
  34656. */
  34657. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34658. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34659. if (!this.IsGlobal) {
  34660. var boundingInfo = this.getBoundingInfo();
  34661. if (!boundingInfo) {
  34662. return result;
  34663. }
  34664. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34665. }
  34666. return result;
  34667. };
  34668. // Dispose
  34669. /**
  34670. * Disposes the Submesh.
  34671. * Returns nothing.
  34672. */
  34673. SubMesh.prototype.dispose = function () {
  34674. if (this._linesIndexBuffer) {
  34675. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34676. this._linesIndexBuffer = null;
  34677. }
  34678. // Remove from mesh
  34679. var index = this._mesh.subMeshes.indexOf(this);
  34680. this._mesh.subMeshes.splice(index, 1);
  34681. };
  34682. // Statics
  34683. /**
  34684. * Creates a new Submesh from the passed parameters :
  34685. * - materialIndex (integer) : the index of the main mesh material.
  34686. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34687. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34688. * - mesh (Mesh) : the main mesh to create the submesh from.
  34689. * - renderingMesh (optional Mesh) : rendering mesh.
  34690. */
  34691. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34692. var minVertexIndex = Number.MAX_VALUE;
  34693. var maxVertexIndex = -Number.MAX_VALUE;
  34694. renderingMesh = (renderingMesh || mesh);
  34695. var indices = renderingMesh.getIndices();
  34696. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34697. var vertexIndex = indices[index];
  34698. if (vertexIndex < minVertexIndex)
  34699. minVertexIndex = vertexIndex;
  34700. if (vertexIndex > maxVertexIndex)
  34701. maxVertexIndex = vertexIndex;
  34702. }
  34703. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34704. };
  34705. return SubMesh;
  34706. }(BaseSubMesh));
  34707. BABYLON.SubMesh = SubMesh;
  34708. })(BABYLON || (BABYLON = {}));
  34709. //# sourceMappingURL=babylon.subMesh.js.map
  34710. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34711. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34712. s = arguments[i];
  34713. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34714. t[p] = s[p];
  34715. }
  34716. return t;
  34717. };
  34718. var BABYLON;
  34719. (function (BABYLON) {
  34720. /**
  34721. * Manages the defines for the Material
  34722. */
  34723. var MaterialDefines = /** @class */ (function () {
  34724. function MaterialDefines() {
  34725. this._isDirty = true;
  34726. /** @hidden */
  34727. this._areLightsDirty = true;
  34728. /** @hidden */
  34729. this._areAttributesDirty = true;
  34730. /** @hidden */
  34731. this._areTexturesDirty = true;
  34732. /** @hidden */
  34733. this._areFresnelDirty = true;
  34734. /** @hidden */
  34735. this._areMiscDirty = true;
  34736. /** @hidden */
  34737. this._areImageProcessingDirty = true;
  34738. /** @hidden */
  34739. this._normals = false;
  34740. /** @hidden */
  34741. this._uvs = false;
  34742. /** @hidden */
  34743. this._needNormals = false;
  34744. /** @hidden */
  34745. this._needUVs = false;
  34746. }
  34747. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34748. /**
  34749. * Specifies if the material needs to be re-calculated
  34750. */
  34751. get: function () {
  34752. return this._isDirty;
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. /**
  34758. * Marks the material to indicate that it has been re-calculated
  34759. */
  34760. MaterialDefines.prototype.markAsProcessed = function () {
  34761. this._isDirty = false;
  34762. this._areAttributesDirty = false;
  34763. this._areTexturesDirty = false;
  34764. this._areFresnelDirty = false;
  34765. this._areLightsDirty = false;
  34766. this._areMiscDirty = false;
  34767. this._areImageProcessingDirty = false;
  34768. };
  34769. /**
  34770. * Marks the material to indicate that it needs to be re-calculated
  34771. */
  34772. MaterialDefines.prototype.markAsUnprocessed = function () {
  34773. this._isDirty = true;
  34774. };
  34775. /**
  34776. * Marks the material to indicate all of its defines need to be re-calculated
  34777. */
  34778. MaterialDefines.prototype.markAllAsDirty = function () {
  34779. this._areTexturesDirty = true;
  34780. this._areAttributesDirty = true;
  34781. this._areLightsDirty = true;
  34782. this._areFresnelDirty = true;
  34783. this._areMiscDirty = true;
  34784. this._areImageProcessingDirty = true;
  34785. this._isDirty = true;
  34786. };
  34787. /**
  34788. * Marks the material to indicate that image processing needs to be re-calculated
  34789. */
  34790. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34791. this._areImageProcessingDirty = true;
  34792. this._isDirty = true;
  34793. };
  34794. /**
  34795. * Marks the material to indicate the lights need to be re-calculated
  34796. */
  34797. MaterialDefines.prototype.markAsLightDirty = function () {
  34798. this._areLightsDirty = true;
  34799. this._isDirty = true;
  34800. };
  34801. /**
  34802. * Marks the attribute state as changed
  34803. */
  34804. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34805. this._areAttributesDirty = true;
  34806. this._isDirty = true;
  34807. };
  34808. /**
  34809. * Marks the texture state as changed
  34810. */
  34811. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34812. this._areTexturesDirty = true;
  34813. this._isDirty = true;
  34814. };
  34815. /**
  34816. * Marks the fresnel state as changed
  34817. */
  34818. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34819. this._areFresnelDirty = true;
  34820. this._isDirty = true;
  34821. };
  34822. /**
  34823. * Marks the misc state as changed
  34824. */
  34825. MaterialDefines.prototype.markAsMiscDirty = function () {
  34826. this._areMiscDirty = true;
  34827. this._isDirty = true;
  34828. };
  34829. /**
  34830. * Rebuilds the material defines
  34831. */
  34832. MaterialDefines.prototype.rebuild = function () {
  34833. if (this._keys) {
  34834. delete this._keys;
  34835. }
  34836. this._keys = [];
  34837. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34838. var key = _a[_i];
  34839. if (key[0] === "_") {
  34840. continue;
  34841. }
  34842. this._keys.push(key);
  34843. }
  34844. };
  34845. /**
  34846. * Specifies if two material defines are equal
  34847. * @param other - A material define instance to compare to
  34848. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34849. */
  34850. MaterialDefines.prototype.isEqual = function (other) {
  34851. if (this._keys.length !== other._keys.length) {
  34852. return false;
  34853. }
  34854. for (var index = 0; index < this._keys.length; index++) {
  34855. var prop = this._keys[index];
  34856. if (this[prop] !== other[prop]) {
  34857. return false;
  34858. }
  34859. }
  34860. return true;
  34861. };
  34862. /**
  34863. * Clones this instance's defines to another instance
  34864. * @param other - material defines to clone values to
  34865. */
  34866. MaterialDefines.prototype.cloneTo = function (other) {
  34867. if (this._keys.length !== other._keys.length) {
  34868. other._keys = this._keys.slice(0);
  34869. }
  34870. for (var index = 0; index < this._keys.length; index++) {
  34871. var prop = this._keys[index];
  34872. other[prop] = this[prop];
  34873. }
  34874. };
  34875. /**
  34876. * Resets the material define values
  34877. */
  34878. MaterialDefines.prototype.reset = function () {
  34879. for (var index = 0; index < this._keys.length; index++) {
  34880. var prop = this._keys[index];
  34881. var type = typeof this[prop];
  34882. switch (type) {
  34883. case "number":
  34884. this[prop] = 0;
  34885. break;
  34886. case "string":
  34887. this[prop] = "";
  34888. break;
  34889. default:
  34890. this[prop] = false;
  34891. break;
  34892. }
  34893. }
  34894. };
  34895. /**
  34896. * Converts the material define values to a string
  34897. * @returns - String of material define information
  34898. */
  34899. MaterialDefines.prototype.toString = function () {
  34900. var result = "";
  34901. for (var index = 0; index < this._keys.length; index++) {
  34902. var prop = this._keys[index];
  34903. var value = this[prop];
  34904. var type = typeof value;
  34905. switch (type) {
  34906. case "number":
  34907. case "string":
  34908. result += "#define " + prop + " " + value + "\n";
  34909. break;
  34910. default:
  34911. if (value) {
  34912. result += "#define " + prop + "\n";
  34913. }
  34914. break;
  34915. }
  34916. }
  34917. return result;
  34918. };
  34919. return MaterialDefines;
  34920. }());
  34921. BABYLON.MaterialDefines = MaterialDefines;
  34922. /**
  34923. * Base class for the main features of a material in Babylon.js
  34924. */
  34925. var Material = /** @class */ (function () {
  34926. /**
  34927. * Creates a material instance
  34928. * @param name defines the name of the material
  34929. * @param scene defines the scene to reference
  34930. * @param doNotAdd specifies if the material should be added to the scene
  34931. */
  34932. function Material(name, scene, doNotAdd) {
  34933. /**
  34934. * Specifies if the ready state should be checked on each call
  34935. */
  34936. this.checkReadyOnEveryCall = false;
  34937. /**
  34938. * Specifies if the ready state should be checked once
  34939. */
  34940. this.checkReadyOnlyOnce = false;
  34941. /**
  34942. * The state of the material
  34943. */
  34944. this.state = "";
  34945. /**
  34946. * The alpha value of the material
  34947. */
  34948. this._alpha = 1.0;
  34949. /**
  34950. * Specifies if back face culling is enabled
  34951. */
  34952. this._backFaceCulling = true;
  34953. /**
  34954. * Specifies if the material should be serialized
  34955. */
  34956. this.doNotSerialize = false;
  34957. /**
  34958. * Specifies if the effect should be stored on sub meshes
  34959. */
  34960. this.storeEffectOnSubMeshes = false;
  34961. /**
  34962. * An event triggered when the material is disposed
  34963. */
  34964. this.onDisposeObservable = new BABYLON.Observable();
  34965. /**
  34966. * An event triggered when the material is bound
  34967. */
  34968. this.onBindObservable = new BABYLON.Observable();
  34969. /**
  34970. * An event triggered when the material is unbound
  34971. */
  34972. this.onUnBindObservable = new BABYLON.Observable();
  34973. /**
  34974. * Stores the value of the alpha mode
  34975. */
  34976. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34977. /**
  34978. * Stores the state of the need depth pre-pass value
  34979. */
  34980. this._needDepthPrePass = false;
  34981. /**
  34982. * Specifies if depth writing should be disabled
  34983. */
  34984. this.disableDepthWrite = false;
  34985. /**
  34986. * Specifies if depth writing should be forced
  34987. */
  34988. this.forceDepthWrite = false;
  34989. /**
  34990. * Specifies if there should be a separate pass for culling
  34991. */
  34992. this.separateCullingPass = false;
  34993. /**
  34994. * Stores the state specifing if fog should be enabled
  34995. */
  34996. this._fogEnabled = true;
  34997. /**
  34998. * Stores the size of points
  34999. */
  35000. this.pointSize = 1.0;
  35001. /**
  35002. * Stores the z offset value
  35003. */
  35004. this.zOffset = 0;
  35005. /**
  35006. * Specifies if the material was previously ready
  35007. */
  35008. this._wasPreviouslyReady = false;
  35009. /**
  35010. * Stores the fill mode state
  35011. */
  35012. this._fillMode = Material.TriangleFillMode;
  35013. this.name = name;
  35014. this.id = name || BABYLON.Tools.RandomId();
  35015. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35016. this.uniqueId = this._scene.getUniqueId();
  35017. if (this._scene.useRightHandedSystem) {
  35018. this.sideOrientation = Material.ClockWiseSideOrientation;
  35019. }
  35020. else {
  35021. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35022. }
  35023. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35024. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35025. if (!doNotAdd) {
  35026. this._scene.materials.push(this);
  35027. }
  35028. }
  35029. Object.defineProperty(Material, "TriangleFillMode", {
  35030. /**
  35031. * Returns the triangle fill mode
  35032. */
  35033. get: function () {
  35034. return Material._TriangleFillMode;
  35035. },
  35036. enumerable: true,
  35037. configurable: true
  35038. });
  35039. Object.defineProperty(Material, "WireFrameFillMode", {
  35040. /**
  35041. * Returns the wireframe mode
  35042. */
  35043. get: function () {
  35044. return Material._WireFrameFillMode;
  35045. },
  35046. enumerable: true,
  35047. configurable: true
  35048. });
  35049. Object.defineProperty(Material, "PointFillMode", {
  35050. /**
  35051. * Returns the point fill mode
  35052. */
  35053. get: function () {
  35054. return Material._PointFillMode;
  35055. },
  35056. enumerable: true,
  35057. configurable: true
  35058. });
  35059. Object.defineProperty(Material, "PointListDrawMode", {
  35060. /**
  35061. * Returns the point list draw mode
  35062. */
  35063. get: function () {
  35064. return Material._PointListDrawMode;
  35065. },
  35066. enumerable: true,
  35067. configurable: true
  35068. });
  35069. Object.defineProperty(Material, "LineListDrawMode", {
  35070. /**
  35071. * Returns the line list draw mode
  35072. */
  35073. get: function () {
  35074. return Material._LineListDrawMode;
  35075. },
  35076. enumerable: true,
  35077. configurable: true
  35078. });
  35079. Object.defineProperty(Material, "LineLoopDrawMode", {
  35080. /**
  35081. * Returns the line loop draw mode
  35082. */
  35083. get: function () {
  35084. return Material._LineLoopDrawMode;
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. Object.defineProperty(Material, "LineStripDrawMode", {
  35090. /**
  35091. * Returns the line strip draw mode
  35092. */
  35093. get: function () {
  35094. return Material._LineStripDrawMode;
  35095. },
  35096. enumerable: true,
  35097. configurable: true
  35098. });
  35099. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35100. /**
  35101. * Returns the triangle strip draw mode
  35102. */
  35103. get: function () {
  35104. return Material._TriangleStripDrawMode;
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35110. /**
  35111. * Returns the triangle fan draw mode
  35112. */
  35113. get: function () {
  35114. return Material._TriangleFanDrawMode;
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35120. /**
  35121. * Returns the clock-wise side orientation
  35122. */
  35123. get: function () {
  35124. return Material._ClockWiseSideOrientation;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35130. /**
  35131. * Returns the counter clock-wise side orientation
  35132. */
  35133. get: function () {
  35134. return Material._CounterClockWiseSideOrientation;
  35135. },
  35136. enumerable: true,
  35137. configurable: true
  35138. });
  35139. Object.defineProperty(Material, "TextureDirtyFlag", {
  35140. /**
  35141. * Returns the dirty texture flag value
  35142. */
  35143. get: function () {
  35144. return Material._TextureDirtyFlag;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material, "LightDirtyFlag", {
  35150. /**
  35151. * Returns the dirty light flag value
  35152. */
  35153. get: function () {
  35154. return Material._LightDirtyFlag;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35160. /**
  35161. * Returns the dirty fresnel flag value
  35162. */
  35163. get: function () {
  35164. return Material._FresnelDirtyFlag;
  35165. },
  35166. enumerable: true,
  35167. configurable: true
  35168. });
  35169. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35170. /**
  35171. * Returns the dirty attributes flag value
  35172. */
  35173. get: function () {
  35174. return Material._AttributesDirtyFlag;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(Material, "MiscDirtyFlag", {
  35180. /**
  35181. * Returns the dirty misc flag value
  35182. */
  35183. get: function () {
  35184. return Material._MiscDirtyFlag;
  35185. },
  35186. enumerable: true,
  35187. configurable: true
  35188. });
  35189. Object.defineProperty(Material.prototype, "alpha", {
  35190. /**
  35191. * Gets the alpha value of the material
  35192. */
  35193. get: function () {
  35194. return this._alpha;
  35195. },
  35196. /**
  35197. * Sets the alpha value of the material
  35198. */
  35199. set: function (value) {
  35200. if (this._alpha === value) {
  35201. return;
  35202. }
  35203. this._alpha = value;
  35204. this.markAsDirty(Material.MiscDirtyFlag);
  35205. },
  35206. enumerable: true,
  35207. configurable: true
  35208. });
  35209. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35210. /**
  35211. * Gets the back-face culling state
  35212. */
  35213. get: function () {
  35214. return this._backFaceCulling;
  35215. },
  35216. /**
  35217. * Sets the back-face culling state
  35218. */
  35219. set: function (value) {
  35220. if (this._backFaceCulling === value) {
  35221. return;
  35222. }
  35223. this._backFaceCulling = value;
  35224. this.markAsDirty(Material.TextureDirtyFlag);
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. Object.defineProperty(Material.prototype, "onDispose", {
  35230. /**
  35231. * Called during a dispose event
  35232. */
  35233. set: function (callback) {
  35234. if (this._onDisposeObserver) {
  35235. this.onDisposeObservable.remove(this._onDisposeObserver);
  35236. }
  35237. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35238. },
  35239. enumerable: true,
  35240. configurable: true
  35241. });
  35242. Object.defineProperty(Material.prototype, "onBind", {
  35243. /**
  35244. * Called during a bind event
  35245. */
  35246. set: function (callback) {
  35247. if (this._onBindObserver) {
  35248. this.onBindObservable.remove(this._onBindObserver);
  35249. }
  35250. this._onBindObserver = this.onBindObservable.add(callback);
  35251. },
  35252. enumerable: true,
  35253. configurable: true
  35254. });
  35255. Object.defineProperty(Material.prototype, "alphaMode", {
  35256. /**
  35257. * Gets the value of the alpha mode
  35258. */
  35259. get: function () {
  35260. return this._alphaMode;
  35261. },
  35262. /**
  35263. * Sets the value of the alpha mode.
  35264. *
  35265. * | Value | Type | Description |
  35266. * | --- | --- | --- |
  35267. * | 0 | ALPHA_DISABLE | |
  35268. * | 1 | ALPHA_ADD | |
  35269. * | 2 | ALPHA_COMBINE | |
  35270. * | 3 | ALPHA_SUBTRACT | |
  35271. * | 4 | ALPHA_MULTIPLY | |
  35272. * | 5 | ALPHA_MAXIMIZED | |
  35273. * | 6 | ALPHA_ONEONE | |
  35274. * | 7 | ALPHA_PREMULTIPLIED | |
  35275. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35276. * | 9 | ALPHA_INTERPOLATE | |
  35277. * | 10 | ALPHA_SCREENMODE | |
  35278. *
  35279. */
  35280. set: function (value) {
  35281. if (this._alphaMode === value) {
  35282. return;
  35283. }
  35284. this._alphaMode = value;
  35285. this.markAsDirty(Material.TextureDirtyFlag);
  35286. },
  35287. enumerable: true,
  35288. configurable: true
  35289. });
  35290. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35291. /**
  35292. * Gets the depth pre-pass value
  35293. */
  35294. get: function () {
  35295. return this._needDepthPrePass;
  35296. },
  35297. /**
  35298. * Sets the need depth pre-pass value
  35299. */
  35300. set: function (value) {
  35301. if (this._needDepthPrePass === value) {
  35302. return;
  35303. }
  35304. this._needDepthPrePass = value;
  35305. if (this._needDepthPrePass) {
  35306. this.checkReadyOnEveryCall = true;
  35307. }
  35308. },
  35309. enumerable: true,
  35310. configurable: true
  35311. });
  35312. Object.defineProperty(Material.prototype, "fogEnabled", {
  35313. /**
  35314. * Gets the value of the fog enabled state
  35315. */
  35316. get: function () {
  35317. return this._fogEnabled;
  35318. },
  35319. /**
  35320. * Sets the state for enabling fog
  35321. */
  35322. set: function (value) {
  35323. if (this._fogEnabled === value) {
  35324. return;
  35325. }
  35326. this._fogEnabled = value;
  35327. this.markAsDirty(Material.MiscDirtyFlag);
  35328. },
  35329. enumerable: true,
  35330. configurable: true
  35331. });
  35332. Object.defineProperty(Material.prototype, "wireframe", {
  35333. /**
  35334. * Gets a value specifying if wireframe mode is enabled
  35335. */
  35336. get: function () {
  35337. switch (this._fillMode) {
  35338. case Material.WireFrameFillMode:
  35339. case Material.LineListDrawMode:
  35340. case Material.LineLoopDrawMode:
  35341. case Material.LineStripDrawMode:
  35342. return true;
  35343. }
  35344. return this._scene.forceWireframe;
  35345. },
  35346. /**
  35347. * Sets the state of wireframe mode
  35348. */
  35349. set: function (value) {
  35350. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35351. },
  35352. enumerable: true,
  35353. configurable: true
  35354. });
  35355. Object.defineProperty(Material.prototype, "pointsCloud", {
  35356. /**
  35357. * Gets the value specifying if point clouds are enabled
  35358. */
  35359. get: function () {
  35360. switch (this._fillMode) {
  35361. case Material.PointFillMode:
  35362. case Material.PointListDrawMode:
  35363. return true;
  35364. }
  35365. return this._scene.forcePointsCloud;
  35366. },
  35367. /**
  35368. * Sets the state of point cloud mode
  35369. */
  35370. set: function (value) {
  35371. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35372. },
  35373. enumerable: true,
  35374. configurable: true
  35375. });
  35376. Object.defineProperty(Material.prototype, "fillMode", {
  35377. /**
  35378. * Gets the material fill mode
  35379. */
  35380. get: function () {
  35381. return this._fillMode;
  35382. },
  35383. /**
  35384. * Sets the material fill mode
  35385. */
  35386. set: function (value) {
  35387. if (this._fillMode === value) {
  35388. return;
  35389. }
  35390. this._fillMode = value;
  35391. this.markAsDirty(Material.MiscDirtyFlag);
  35392. },
  35393. enumerable: true,
  35394. configurable: true
  35395. });
  35396. /**
  35397. * Returns a string representation of the current material
  35398. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35399. * @returns a string with material information
  35400. */
  35401. Material.prototype.toString = function (fullDetails) {
  35402. var ret = "Name: " + this.name;
  35403. if (fullDetails) {
  35404. }
  35405. return ret;
  35406. };
  35407. /**
  35408. * Gets the class name of the material
  35409. * @returns a string with the class name of the material
  35410. */
  35411. Material.prototype.getClassName = function () {
  35412. return "Material";
  35413. };
  35414. Object.defineProperty(Material.prototype, "isFrozen", {
  35415. /**
  35416. * Specifies if updates for the material been locked
  35417. */
  35418. get: function () {
  35419. return this.checkReadyOnlyOnce;
  35420. },
  35421. enumerable: true,
  35422. configurable: true
  35423. });
  35424. /**
  35425. * Locks updates for the material
  35426. */
  35427. Material.prototype.freeze = function () {
  35428. this.checkReadyOnlyOnce = true;
  35429. };
  35430. /**
  35431. * Unlocks updates for the material
  35432. */
  35433. Material.prototype.unfreeze = function () {
  35434. this.checkReadyOnlyOnce = false;
  35435. };
  35436. /**
  35437. * Specifies if the material is ready to be used
  35438. * @param mesh defines the mesh to check
  35439. * @param useInstances specifies if instances should be used
  35440. * @returns a boolean indicating if the material is ready to be used
  35441. */
  35442. Material.prototype.isReady = function (mesh, useInstances) {
  35443. return true;
  35444. };
  35445. /**
  35446. * Specifies that the submesh is ready to be used
  35447. * @param mesh defines the mesh to check
  35448. * @param subMesh defines which submesh to check
  35449. * @param useInstances specifies that instances should be used
  35450. * @returns a boolean indicating that the submesh is ready or not
  35451. */
  35452. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35453. return false;
  35454. };
  35455. /**
  35456. * Returns the material effect
  35457. * @returns the effect associated with the material
  35458. */
  35459. Material.prototype.getEffect = function () {
  35460. return this._effect;
  35461. };
  35462. /**
  35463. * Returns the current scene
  35464. * @returns a Scene
  35465. */
  35466. Material.prototype.getScene = function () {
  35467. return this._scene;
  35468. };
  35469. /**
  35470. * Specifies if the material will require alpha blending
  35471. * @returns a boolean specifying if alpha blending is needed
  35472. */
  35473. Material.prototype.needAlphaBlending = function () {
  35474. return (this.alpha < 1.0);
  35475. };
  35476. /**
  35477. * Specifies if the mesh will require alpha blending
  35478. * @param mesh defines the mesh to check
  35479. * @returns a boolean specifying if alpha blending is needed for the mesh
  35480. */
  35481. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35482. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35483. };
  35484. /**
  35485. * Specifies if this material should be rendered in alpha test mode
  35486. * @returns a boolean specifying if an alpha test is needed.
  35487. */
  35488. Material.prototype.needAlphaTesting = function () {
  35489. return false;
  35490. };
  35491. /**
  35492. * Gets the texture used for the alpha test
  35493. * @returns the texture to use for alpha testing
  35494. */
  35495. Material.prototype.getAlphaTestTexture = function () {
  35496. return null;
  35497. };
  35498. /**
  35499. * Marks the material to indicate that it needs to be re-calculated
  35500. */
  35501. Material.prototype.markDirty = function () {
  35502. this._wasPreviouslyReady = false;
  35503. };
  35504. /** @hidden */
  35505. Material.prototype._preBind = function (effect, overrideOrientation) {
  35506. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35507. var engine = this._scene.getEngine();
  35508. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35509. var reverse = orientation === Material.ClockWiseSideOrientation;
  35510. engine.enableEffect(effect ? effect : this._effect);
  35511. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35512. return reverse;
  35513. };
  35514. /**
  35515. * Binds the material to the mesh
  35516. * @param world defines the world transformation matrix
  35517. * @param mesh defines the mesh to bind the material to
  35518. */
  35519. Material.prototype.bind = function (world, mesh) {
  35520. };
  35521. /**
  35522. * Binds the submesh to the material
  35523. * @param world defines the world transformation matrix
  35524. * @param mesh defines the mesh containing the submesh
  35525. * @param subMesh defines the submesh to bind the material to
  35526. */
  35527. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35528. };
  35529. /**
  35530. * Binds the world matrix to the material
  35531. * @param world defines the world transformation matrix
  35532. */
  35533. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35534. };
  35535. /**
  35536. * Binds the scene's uniform buffer to the effect.
  35537. * @param effect defines the effect to bind to the scene uniform buffer
  35538. * @param sceneUbo defines the uniform buffer storing scene data
  35539. */
  35540. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35541. sceneUbo.bindToEffect(effect, "Scene");
  35542. };
  35543. /**
  35544. * Binds the view matrix to the effect
  35545. * @param effect defines the effect to bind the view matrix to
  35546. */
  35547. Material.prototype.bindView = function (effect) {
  35548. if (!this._useUBO) {
  35549. effect.setMatrix("view", this.getScene().getViewMatrix());
  35550. }
  35551. else {
  35552. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35553. }
  35554. };
  35555. /**
  35556. * Binds the view projection matrix to the effect
  35557. * @param effect defines the effect to bind the view projection matrix to
  35558. */
  35559. Material.prototype.bindViewProjection = function (effect) {
  35560. if (!this._useUBO) {
  35561. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35562. }
  35563. else {
  35564. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35565. }
  35566. };
  35567. /**
  35568. * Specifies if material alpha testing should be turned on for the mesh
  35569. * @param mesh defines the mesh to check
  35570. */
  35571. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35572. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35573. };
  35574. /**
  35575. * Processes to execute after binding the material to a mesh
  35576. * @param mesh defines the rendered mesh
  35577. */
  35578. Material.prototype._afterBind = function (mesh) {
  35579. this._scene._cachedMaterial = this;
  35580. if (mesh) {
  35581. this._scene._cachedVisibility = mesh.visibility;
  35582. }
  35583. else {
  35584. this._scene._cachedVisibility = 1;
  35585. }
  35586. if (mesh) {
  35587. this.onBindObservable.notifyObservers(mesh);
  35588. }
  35589. if (this.disableDepthWrite) {
  35590. var engine = this._scene.getEngine();
  35591. this._cachedDepthWriteState = engine.getDepthWrite();
  35592. engine.setDepthWrite(false);
  35593. }
  35594. };
  35595. /**
  35596. * Unbinds the material from the mesh
  35597. */
  35598. Material.prototype.unbind = function () {
  35599. this.onUnBindObservable.notifyObservers(this);
  35600. if (this.disableDepthWrite) {
  35601. var engine = this._scene.getEngine();
  35602. engine.setDepthWrite(this._cachedDepthWriteState);
  35603. }
  35604. };
  35605. /**
  35606. * Gets the active textures from the material
  35607. * @returns an array of textures
  35608. */
  35609. Material.prototype.getActiveTextures = function () {
  35610. return [];
  35611. };
  35612. /**
  35613. * Specifies if the material uses a texture
  35614. * @param texture defines the texture to check against the material
  35615. * @returns a boolean specifying if the material uses the texture
  35616. */
  35617. Material.prototype.hasTexture = function (texture) {
  35618. return false;
  35619. };
  35620. /**
  35621. * Makes a duplicate of the material, and gives it a new name
  35622. * @param name defines the new name for the duplicated material
  35623. * @returns the cloned material
  35624. */
  35625. Material.prototype.clone = function (name) {
  35626. return null;
  35627. };
  35628. /**
  35629. * Gets the meshes bound to the material
  35630. * @returns an array of meshes bound to the material
  35631. */
  35632. Material.prototype.getBindedMeshes = function () {
  35633. var result = new Array();
  35634. for (var index = 0; index < this._scene.meshes.length; index++) {
  35635. var mesh = this._scene.meshes[index];
  35636. if (mesh.material === this) {
  35637. result.push(mesh);
  35638. }
  35639. }
  35640. return result;
  35641. };
  35642. /**
  35643. * Force shader compilation
  35644. * @param mesh defines the mesh associated with this material
  35645. * @param onCompiled defines a function to execute once the material is compiled
  35646. * @param options defines the options to configure the compilation
  35647. */
  35648. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35649. var _this = this;
  35650. var localOptions = __assign({ clipPlane: false }, options);
  35651. var subMesh = new BABYLON.BaseSubMesh();
  35652. var scene = this.getScene();
  35653. var checkReady = function () {
  35654. if (!_this._scene || !_this._scene.getEngine()) {
  35655. return;
  35656. }
  35657. if (subMesh._materialDefines) {
  35658. subMesh._materialDefines._renderId = -1;
  35659. }
  35660. var clipPlaneState = scene.clipPlane;
  35661. if (localOptions.clipPlane) {
  35662. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35663. }
  35664. if (_this.storeEffectOnSubMeshes) {
  35665. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35666. if (onCompiled) {
  35667. onCompiled(_this);
  35668. }
  35669. }
  35670. else {
  35671. setTimeout(checkReady, 16);
  35672. }
  35673. }
  35674. else {
  35675. if (_this.isReady(mesh)) {
  35676. if (onCompiled) {
  35677. onCompiled(_this);
  35678. }
  35679. }
  35680. else {
  35681. setTimeout(checkReady, 16);
  35682. }
  35683. }
  35684. if (localOptions.clipPlane) {
  35685. scene.clipPlane = clipPlaneState;
  35686. }
  35687. };
  35688. checkReady();
  35689. };
  35690. /**
  35691. * Force shader compilation
  35692. * @param mesh defines the mesh that will use this material
  35693. * @param options defines additional options for compiling the shaders
  35694. * @returns a promise that resolves when the compilation completes
  35695. */
  35696. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35697. var _this = this;
  35698. return new Promise(function (resolve) {
  35699. _this.forceCompilation(mesh, function () {
  35700. resolve();
  35701. }, options);
  35702. });
  35703. };
  35704. /**
  35705. * Marks a define in the material to indicate that it needs to be re-computed
  35706. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35707. */
  35708. Material.prototype.markAsDirty = function (flag) {
  35709. if (flag & Material.TextureDirtyFlag) {
  35710. this._markAllSubMeshesAsTexturesDirty();
  35711. }
  35712. if (flag & Material.LightDirtyFlag) {
  35713. this._markAllSubMeshesAsLightsDirty();
  35714. }
  35715. if (flag & Material.FresnelDirtyFlag) {
  35716. this._markAllSubMeshesAsFresnelDirty();
  35717. }
  35718. if (flag & Material.AttributesDirtyFlag) {
  35719. this._markAllSubMeshesAsAttributesDirty();
  35720. }
  35721. if (flag & Material.MiscDirtyFlag) {
  35722. this._markAllSubMeshesAsMiscDirty();
  35723. }
  35724. this.getScene().resetCachedMaterial();
  35725. };
  35726. /**
  35727. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35728. * @param func defines a function which checks material defines against the submeshes
  35729. */
  35730. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35731. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35732. var mesh = _a[_i];
  35733. if (!mesh.subMeshes) {
  35734. continue;
  35735. }
  35736. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35737. var subMesh = _c[_b];
  35738. if (subMesh.getMaterial() !== this) {
  35739. continue;
  35740. }
  35741. if (!subMesh._materialDefines) {
  35742. continue;
  35743. }
  35744. func(subMesh._materialDefines);
  35745. }
  35746. }
  35747. };
  35748. /**
  35749. * Indicates that image processing needs to be re-calculated for all submeshes
  35750. */
  35751. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35752. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35753. };
  35754. /**
  35755. * Indicates that textures need to be re-calculated for all submeshes
  35756. */
  35757. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35758. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35759. };
  35760. /**
  35761. * Indicates that fresnel needs to be re-calculated for all submeshes
  35762. */
  35763. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35764. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35765. };
  35766. /**
  35767. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35768. */
  35769. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35770. this._markAllSubMeshesAsDirty(function (defines) {
  35771. defines.markAsFresnelDirty();
  35772. defines.markAsMiscDirty();
  35773. });
  35774. };
  35775. /**
  35776. * Indicates that lights need to be re-calculated for all submeshes
  35777. */
  35778. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35779. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35780. };
  35781. /**
  35782. * Indicates that attributes need to be re-calculated for all submeshes
  35783. */
  35784. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35785. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35786. };
  35787. /**
  35788. * Indicates that misc needs to be re-calculated for all submeshes
  35789. */
  35790. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35791. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35792. };
  35793. /**
  35794. * Indicates that textures and misc need to be re-calculated for all submeshes
  35795. */
  35796. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35797. this._markAllSubMeshesAsDirty(function (defines) {
  35798. defines.markAsTexturesDirty();
  35799. defines.markAsMiscDirty();
  35800. });
  35801. };
  35802. /**
  35803. * Disposes the material
  35804. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35805. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35806. */
  35807. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35808. // Animations
  35809. this.getScene().stopAnimation(this);
  35810. this.getScene().freeProcessedMaterials();
  35811. // Remove from scene
  35812. var index = this._scene.materials.indexOf(this);
  35813. if (index >= 0) {
  35814. this._scene.materials.splice(index, 1);
  35815. }
  35816. // Remove from meshes
  35817. for (index = 0; index < this._scene.meshes.length; index++) {
  35818. var mesh = this._scene.meshes[index];
  35819. if (mesh.material === this) {
  35820. mesh.material = null;
  35821. if (mesh.geometry) {
  35822. var geometry = (mesh.geometry);
  35823. if (this.storeEffectOnSubMeshes) {
  35824. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35825. var subMesh = _a[_i];
  35826. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35827. if (forceDisposeEffect && subMesh._materialEffect) {
  35828. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35829. }
  35830. }
  35831. }
  35832. else {
  35833. geometry._releaseVertexArrayObject(this._effect);
  35834. }
  35835. }
  35836. }
  35837. }
  35838. this._uniformBuffer.dispose();
  35839. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35840. if (forceDisposeEffect && this._effect) {
  35841. if (!this.storeEffectOnSubMeshes) {
  35842. this._scene.getEngine()._releaseEffect(this._effect);
  35843. }
  35844. this._effect = null;
  35845. }
  35846. // Callback
  35847. this.onDisposeObservable.notifyObservers(this);
  35848. this.onDisposeObservable.clear();
  35849. this.onBindObservable.clear();
  35850. this.onUnBindObservable.clear();
  35851. };
  35852. /**
  35853. * Serializes this material
  35854. * @returns the serialized material object
  35855. */
  35856. Material.prototype.serialize = function () {
  35857. return BABYLON.SerializationHelper.Serialize(this);
  35858. };
  35859. /**
  35860. * Creates a MultiMaterial from parsed MultiMaterial data.
  35861. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35862. * @param scene defines the hosting scene
  35863. * @returns a new MultiMaterial
  35864. */
  35865. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35866. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35867. multiMaterial.id = parsedMultiMaterial.id;
  35868. if (BABYLON.Tags) {
  35869. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35870. }
  35871. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35872. var subMatId = parsedMultiMaterial.materials[matIndex];
  35873. if (subMatId) {
  35874. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35875. }
  35876. else {
  35877. multiMaterial.subMaterials.push(null);
  35878. }
  35879. }
  35880. return multiMaterial;
  35881. };
  35882. /**
  35883. * Creates a material from parsed material data
  35884. * @param parsedMaterial defines parsed material data
  35885. * @param scene defines the hosting scene
  35886. * @param rootUrl defines the root URL to use to load textures
  35887. * @returns a new material
  35888. */
  35889. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35890. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35891. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35892. }
  35893. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35894. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35895. if (!BABYLON.LegacyPBRMaterial) {
  35896. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35897. return;
  35898. }
  35899. }
  35900. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35901. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35902. };
  35903. // Triangle views
  35904. Material._TriangleFillMode = 0;
  35905. Material._WireFrameFillMode = 1;
  35906. Material._PointFillMode = 2;
  35907. // Draw modes
  35908. Material._PointListDrawMode = 3;
  35909. Material._LineListDrawMode = 4;
  35910. Material._LineLoopDrawMode = 5;
  35911. Material._LineStripDrawMode = 6;
  35912. Material._TriangleStripDrawMode = 7;
  35913. Material._TriangleFanDrawMode = 8;
  35914. /**
  35915. * Stores the clock-wise side orientation
  35916. */
  35917. Material._ClockWiseSideOrientation = 0;
  35918. /**
  35919. * Stores the counter clock-wise side orientation
  35920. */
  35921. Material._CounterClockWiseSideOrientation = 1;
  35922. /**
  35923. * The dirty texture flag value
  35924. */
  35925. Material._TextureDirtyFlag = 1;
  35926. /**
  35927. * The dirty light flag value
  35928. */
  35929. Material._LightDirtyFlag = 2;
  35930. /**
  35931. * The dirty fresnel flag value
  35932. */
  35933. Material._FresnelDirtyFlag = 4;
  35934. /**
  35935. * The dirty attribute flag value
  35936. */
  35937. Material._AttributesDirtyFlag = 8;
  35938. /**
  35939. * The dirty misc flag value
  35940. */
  35941. Material._MiscDirtyFlag = 16;
  35942. __decorate([
  35943. BABYLON.serialize()
  35944. ], Material.prototype, "id", void 0);
  35945. __decorate([
  35946. BABYLON.serialize()
  35947. ], Material.prototype, "uniqueId", void 0);
  35948. __decorate([
  35949. BABYLON.serialize()
  35950. ], Material.prototype, "name", void 0);
  35951. __decorate([
  35952. BABYLON.serialize()
  35953. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35954. __decorate([
  35955. BABYLON.serialize()
  35956. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35957. __decorate([
  35958. BABYLON.serialize()
  35959. ], Material.prototype, "state", void 0);
  35960. __decorate([
  35961. BABYLON.serialize("alpha")
  35962. ], Material.prototype, "_alpha", void 0);
  35963. __decorate([
  35964. BABYLON.serialize("backFaceCulling")
  35965. ], Material.prototype, "_backFaceCulling", void 0);
  35966. __decorate([
  35967. BABYLON.serialize()
  35968. ], Material.prototype, "sideOrientation", void 0);
  35969. __decorate([
  35970. BABYLON.serialize("alphaMode")
  35971. ], Material.prototype, "_alphaMode", void 0);
  35972. __decorate([
  35973. BABYLON.serialize()
  35974. ], Material.prototype, "_needDepthPrePass", void 0);
  35975. __decorate([
  35976. BABYLON.serialize()
  35977. ], Material.prototype, "disableDepthWrite", void 0);
  35978. __decorate([
  35979. BABYLON.serialize()
  35980. ], Material.prototype, "forceDepthWrite", void 0);
  35981. __decorate([
  35982. BABYLON.serialize()
  35983. ], Material.prototype, "separateCullingPass", void 0);
  35984. __decorate([
  35985. BABYLON.serialize("fogEnabled")
  35986. ], Material.prototype, "_fogEnabled", void 0);
  35987. __decorate([
  35988. BABYLON.serialize()
  35989. ], Material.prototype, "pointSize", void 0);
  35990. __decorate([
  35991. BABYLON.serialize()
  35992. ], Material.prototype, "zOffset", void 0);
  35993. __decorate([
  35994. BABYLON.serialize()
  35995. ], Material.prototype, "wireframe", null);
  35996. __decorate([
  35997. BABYLON.serialize()
  35998. ], Material.prototype, "pointsCloud", null);
  35999. __decorate([
  36000. BABYLON.serialize()
  36001. ], Material.prototype, "fillMode", null);
  36002. return Material;
  36003. }());
  36004. BABYLON.Material = Material;
  36005. })(BABYLON || (BABYLON = {}));
  36006. //# sourceMappingURL=babylon.material.js.map
  36007. var BABYLON;
  36008. (function (BABYLON) {
  36009. var UniformBuffer = /** @class */ (function () {
  36010. /**
  36011. * Uniform buffer objects.
  36012. *
  36013. * Handles blocks of uniform on the GPU.
  36014. *
  36015. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36016. *
  36017. * For more information, please refer to :
  36018. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36019. */
  36020. function UniformBuffer(engine, data, dynamic) {
  36021. this._engine = engine;
  36022. this._noUBO = !engine.supportsUniformBuffers;
  36023. this._dynamic = dynamic;
  36024. this._data = data || [];
  36025. this._uniformLocations = {};
  36026. this._uniformSizes = {};
  36027. this._uniformLocationPointer = 0;
  36028. this._needSync = false;
  36029. if (this._noUBO) {
  36030. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36031. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36032. this.updateFloat = this._updateFloatForEffect;
  36033. this.updateFloat2 = this._updateFloat2ForEffect;
  36034. this.updateFloat3 = this._updateFloat3ForEffect;
  36035. this.updateFloat4 = this._updateFloat4ForEffect;
  36036. this.updateMatrix = this._updateMatrixForEffect;
  36037. this.updateVector3 = this._updateVector3ForEffect;
  36038. this.updateVector4 = this._updateVector4ForEffect;
  36039. this.updateColor3 = this._updateColor3ForEffect;
  36040. this.updateColor4 = this._updateColor4ForEffect;
  36041. }
  36042. else {
  36043. this._engine._uniformBuffers.push(this);
  36044. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36045. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36046. this.updateFloat = this._updateFloatForUniform;
  36047. this.updateFloat2 = this._updateFloat2ForUniform;
  36048. this.updateFloat3 = this._updateFloat3ForUniform;
  36049. this.updateFloat4 = this._updateFloat4ForUniform;
  36050. this.updateMatrix = this._updateMatrixForUniform;
  36051. this.updateVector3 = this._updateVector3ForUniform;
  36052. this.updateVector4 = this._updateVector4ForUniform;
  36053. this.updateColor3 = this._updateColor3ForUniform;
  36054. this.updateColor4 = this._updateColor4ForUniform;
  36055. }
  36056. }
  36057. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36058. // Properties
  36059. /**
  36060. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36061. * or just falling back on setUniformXXX calls.
  36062. */
  36063. get: function () {
  36064. return !this._noUBO;
  36065. },
  36066. enumerable: true,
  36067. configurable: true
  36068. });
  36069. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36070. /**
  36071. * Indicates if the WebGL underlying uniform buffer is in sync
  36072. * with the javascript cache data.
  36073. */
  36074. get: function () {
  36075. return !this._needSync;
  36076. },
  36077. enumerable: true,
  36078. configurable: true
  36079. });
  36080. /**
  36081. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36082. * Also, a dynamic UniformBuffer will disable cache verification and always
  36083. * update the underlying WebGL uniform buffer to the GPU.
  36084. */
  36085. UniformBuffer.prototype.isDynamic = function () {
  36086. return this._dynamic !== undefined;
  36087. };
  36088. /**
  36089. * The data cache on JS side.
  36090. */
  36091. UniformBuffer.prototype.getData = function () {
  36092. return this._bufferData;
  36093. };
  36094. /**
  36095. * The underlying WebGL Uniform buffer.
  36096. */
  36097. UniformBuffer.prototype.getBuffer = function () {
  36098. return this._buffer;
  36099. };
  36100. /**
  36101. * std140 layout specifies how to align data within an UBO structure.
  36102. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36103. * for specs.
  36104. */
  36105. UniformBuffer.prototype._fillAlignment = function (size) {
  36106. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36107. // and 4x4 matrices
  36108. // TODO : change if other types are used
  36109. var alignment;
  36110. if (size <= 2) {
  36111. alignment = size;
  36112. }
  36113. else {
  36114. alignment = 4;
  36115. }
  36116. if ((this._uniformLocationPointer % alignment) !== 0) {
  36117. var oldPointer = this._uniformLocationPointer;
  36118. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36119. var diff = this._uniformLocationPointer - oldPointer;
  36120. for (var i = 0; i < diff; i++) {
  36121. this._data.push(0);
  36122. }
  36123. }
  36124. };
  36125. /**
  36126. * Adds an uniform in the buffer.
  36127. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36128. * for the layout to be correct !
  36129. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36130. * @param {number|number[]} size Data size, or data directly.
  36131. */
  36132. UniformBuffer.prototype.addUniform = function (name, size) {
  36133. if (this._noUBO) {
  36134. return;
  36135. }
  36136. if (this._uniformLocations[name] !== undefined) {
  36137. // Already existing uniform
  36138. return;
  36139. }
  36140. // This function must be called in the order of the shader layout !
  36141. // size can be the size of the uniform, or data directly
  36142. var data;
  36143. if (size instanceof Array) {
  36144. data = size;
  36145. size = data.length;
  36146. }
  36147. else {
  36148. size = size;
  36149. data = [];
  36150. // Fill with zeros
  36151. for (var i = 0; i < size; i++) {
  36152. data.push(0);
  36153. }
  36154. }
  36155. this._fillAlignment(size);
  36156. this._uniformSizes[name] = size;
  36157. this._uniformLocations[name] = this._uniformLocationPointer;
  36158. this._uniformLocationPointer += size;
  36159. for (var i = 0; i < size; i++) {
  36160. this._data.push(data[i]);
  36161. }
  36162. this._needSync = true;
  36163. };
  36164. /**
  36165. * Wrapper for addUniform.
  36166. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36167. * @param {Matrix} mat A 4x4 matrix.
  36168. */
  36169. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36170. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36171. };
  36172. /**
  36173. * Wrapper for addUniform.
  36174. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36175. * @param {number} x
  36176. * @param {number} y
  36177. */
  36178. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36179. var temp = [x, y];
  36180. this.addUniform(name, temp);
  36181. };
  36182. /**
  36183. * Wrapper for addUniform.
  36184. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36185. * @param {number} x
  36186. * @param {number} y
  36187. * @param {number} z
  36188. */
  36189. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36190. var temp = [x, y, z];
  36191. this.addUniform(name, temp);
  36192. };
  36193. /**
  36194. * Wrapper for addUniform.
  36195. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36196. * @param {Color3} color
  36197. */
  36198. UniformBuffer.prototype.addColor3 = function (name, color) {
  36199. var temp = new Array();
  36200. color.toArray(temp);
  36201. this.addUniform(name, temp);
  36202. };
  36203. /**
  36204. * Wrapper for addUniform.
  36205. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36206. * @param {Color3} color
  36207. * @param {number} alpha
  36208. */
  36209. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36210. var temp = new Array();
  36211. color.toArray(temp);
  36212. temp.push(alpha);
  36213. this.addUniform(name, temp);
  36214. };
  36215. /**
  36216. * Wrapper for addUniform.
  36217. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36218. * @param {Vector3} vector
  36219. */
  36220. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36221. var temp = new Array();
  36222. vector.toArray(temp);
  36223. this.addUniform(name, temp);
  36224. };
  36225. /**
  36226. * Wrapper for addUniform.
  36227. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36228. */
  36229. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36230. this.addUniform(name, 12);
  36231. };
  36232. /**
  36233. * Wrapper for addUniform.
  36234. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36235. */
  36236. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36237. this.addUniform(name, 8);
  36238. };
  36239. /**
  36240. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36241. */
  36242. UniformBuffer.prototype.create = function () {
  36243. if (this._noUBO) {
  36244. return;
  36245. }
  36246. if (this._buffer) {
  36247. return; // nothing to do
  36248. }
  36249. // See spec, alignment must be filled as a vec4
  36250. this._fillAlignment(4);
  36251. this._bufferData = new Float32Array(this._data);
  36252. this._rebuild();
  36253. this._needSync = true;
  36254. };
  36255. UniformBuffer.prototype._rebuild = function () {
  36256. if (this._noUBO) {
  36257. return;
  36258. }
  36259. if (this._dynamic) {
  36260. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36261. }
  36262. else {
  36263. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36264. }
  36265. };
  36266. /**
  36267. * Updates the WebGL Uniform Buffer on the GPU.
  36268. * If the `dynamic` flag is set to true, no cache comparison is done.
  36269. * Otherwise, the buffer will be updated only if the cache differs.
  36270. */
  36271. UniformBuffer.prototype.update = function () {
  36272. if (!this._buffer) {
  36273. this.create();
  36274. return;
  36275. }
  36276. if (!this._dynamic && !this._needSync) {
  36277. return;
  36278. }
  36279. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36280. this._needSync = false;
  36281. };
  36282. /**
  36283. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36284. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36285. * @param {number[]|Float32Array} data Flattened data
  36286. * @param {number} size Size of the data.
  36287. */
  36288. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36289. var location = this._uniformLocations[uniformName];
  36290. if (location === undefined) {
  36291. if (this._buffer) {
  36292. // Cannot add an uniform if the buffer is already created
  36293. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36294. return;
  36295. }
  36296. this.addUniform(uniformName, size);
  36297. location = this._uniformLocations[uniformName];
  36298. }
  36299. if (!this._buffer) {
  36300. this.create();
  36301. }
  36302. if (!this._dynamic) {
  36303. // Cache for static uniform buffers
  36304. var changed = false;
  36305. for (var i = 0; i < size; i++) {
  36306. if (this._bufferData[location + i] !== data[i]) {
  36307. changed = true;
  36308. this._bufferData[location + i] = data[i];
  36309. }
  36310. }
  36311. this._needSync = this._needSync || changed;
  36312. }
  36313. else {
  36314. // No cache for dynamic
  36315. for (var i = 0; i < size; i++) {
  36316. this._bufferData[location + i] = data[i];
  36317. }
  36318. }
  36319. };
  36320. // Update methods
  36321. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36322. // To match std140, matrix must be realigned
  36323. for (var i = 0; i < 3; i++) {
  36324. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36325. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36326. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36327. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36328. }
  36329. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36330. };
  36331. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36332. this._currentEffect.setMatrix3x3(name, matrix);
  36333. };
  36334. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36335. this._currentEffect.setMatrix2x2(name, matrix);
  36336. };
  36337. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36338. // To match std140, matrix must be realigned
  36339. for (var i = 0; i < 2; i++) {
  36340. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36341. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36342. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36343. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36344. }
  36345. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36346. };
  36347. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36348. this._currentEffect.setFloat(name, x);
  36349. };
  36350. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36351. UniformBuffer._tempBuffer[0] = x;
  36352. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36353. };
  36354. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36355. if (suffix === void 0) { suffix = ""; }
  36356. this._currentEffect.setFloat2(name + suffix, x, y);
  36357. };
  36358. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36359. if (suffix === void 0) { suffix = ""; }
  36360. UniformBuffer._tempBuffer[0] = x;
  36361. UniformBuffer._tempBuffer[1] = y;
  36362. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36363. };
  36364. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36365. if (suffix === void 0) { suffix = ""; }
  36366. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36367. };
  36368. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36369. if (suffix === void 0) { suffix = ""; }
  36370. UniformBuffer._tempBuffer[0] = x;
  36371. UniformBuffer._tempBuffer[1] = y;
  36372. UniformBuffer._tempBuffer[2] = z;
  36373. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36374. };
  36375. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36376. if (suffix === void 0) { suffix = ""; }
  36377. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36378. };
  36379. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36380. if (suffix === void 0) { suffix = ""; }
  36381. UniformBuffer._tempBuffer[0] = x;
  36382. UniformBuffer._tempBuffer[1] = y;
  36383. UniformBuffer._tempBuffer[2] = z;
  36384. UniformBuffer._tempBuffer[3] = w;
  36385. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36386. };
  36387. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36388. this._currentEffect.setMatrix(name, mat);
  36389. };
  36390. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36391. this.updateUniform(name, mat.toArray(), 16);
  36392. };
  36393. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36394. this._currentEffect.setVector3(name, vector);
  36395. };
  36396. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36397. vector.toArray(UniformBuffer._tempBuffer);
  36398. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36399. };
  36400. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36401. this._currentEffect.setVector4(name, vector);
  36402. };
  36403. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36404. vector.toArray(UniformBuffer._tempBuffer);
  36405. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36406. };
  36407. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36408. if (suffix === void 0) { suffix = ""; }
  36409. this._currentEffect.setColor3(name + suffix, color);
  36410. };
  36411. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36412. if (suffix === void 0) { suffix = ""; }
  36413. color.toArray(UniformBuffer._tempBuffer);
  36414. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36415. };
  36416. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36417. if (suffix === void 0) { suffix = ""; }
  36418. this._currentEffect.setColor4(name + suffix, color, alpha);
  36419. };
  36420. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36421. if (suffix === void 0) { suffix = ""; }
  36422. color.toArray(UniformBuffer._tempBuffer);
  36423. UniformBuffer._tempBuffer[3] = alpha;
  36424. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36425. };
  36426. /**
  36427. * Sets a sampler uniform on the effect.
  36428. * @param {string} name Name of the sampler.
  36429. * @param {Texture} texture
  36430. */
  36431. UniformBuffer.prototype.setTexture = function (name, texture) {
  36432. this._currentEffect.setTexture(name, texture);
  36433. };
  36434. /**
  36435. * Directly updates the value of the uniform in the cache AND on the GPU.
  36436. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36437. * @param {number[]|Float32Array} data Flattened data
  36438. */
  36439. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36440. this.updateUniform(uniformName, data, data.length);
  36441. this.update();
  36442. };
  36443. /**
  36444. * Binds this uniform buffer to an effect.
  36445. * @param {Effect} effect
  36446. * @param {string} name Name of the uniform block in the shader.
  36447. */
  36448. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36449. this._currentEffect = effect;
  36450. if (this._noUBO || !this._buffer) {
  36451. return;
  36452. }
  36453. effect.bindUniformBuffer(this._buffer, name);
  36454. };
  36455. /**
  36456. * Disposes the uniform buffer.
  36457. */
  36458. UniformBuffer.prototype.dispose = function () {
  36459. if (this._noUBO) {
  36460. return;
  36461. }
  36462. var index = this._engine._uniformBuffers.indexOf(this);
  36463. if (index !== -1) {
  36464. this._engine._uniformBuffers.splice(index, 1);
  36465. }
  36466. if (!this._buffer) {
  36467. return;
  36468. }
  36469. if (this._engine._releaseBuffer(this._buffer)) {
  36470. this._buffer = null;
  36471. }
  36472. };
  36473. // Pool for avoiding memory leaks
  36474. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36475. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36476. return UniformBuffer;
  36477. }());
  36478. BABYLON.UniformBuffer = UniformBuffer;
  36479. })(BABYLON || (BABYLON = {}));
  36480. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36481. var BABYLON;
  36482. (function (BABYLON) {
  36483. /**
  36484. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36485. */
  36486. var VertexData = /** @class */ (function () {
  36487. function VertexData() {
  36488. }
  36489. /**
  36490. * Uses the passed data array to set the set the values for the specified kind of data
  36491. * @param data a linear array of floating numbers
  36492. * @param kind the type of data that is being set, eg positions, colors etc
  36493. */
  36494. VertexData.prototype.set = function (data, kind) {
  36495. switch (kind) {
  36496. case BABYLON.VertexBuffer.PositionKind:
  36497. this.positions = data;
  36498. break;
  36499. case BABYLON.VertexBuffer.NormalKind:
  36500. this.normals = data;
  36501. break;
  36502. case BABYLON.VertexBuffer.TangentKind:
  36503. this.tangents = data;
  36504. break;
  36505. case BABYLON.VertexBuffer.UVKind:
  36506. this.uvs = data;
  36507. break;
  36508. case BABYLON.VertexBuffer.UV2Kind:
  36509. this.uvs2 = data;
  36510. break;
  36511. case BABYLON.VertexBuffer.UV3Kind:
  36512. this.uvs3 = data;
  36513. break;
  36514. case BABYLON.VertexBuffer.UV4Kind:
  36515. this.uvs4 = data;
  36516. break;
  36517. case BABYLON.VertexBuffer.UV5Kind:
  36518. this.uvs5 = data;
  36519. break;
  36520. case BABYLON.VertexBuffer.UV6Kind:
  36521. this.uvs6 = data;
  36522. break;
  36523. case BABYLON.VertexBuffer.ColorKind:
  36524. this.colors = data;
  36525. break;
  36526. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36527. this.matricesIndices = data;
  36528. break;
  36529. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36530. this.matricesWeights = data;
  36531. break;
  36532. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36533. this.matricesIndicesExtra = data;
  36534. break;
  36535. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36536. this.matricesWeightsExtra = data;
  36537. break;
  36538. }
  36539. };
  36540. /**
  36541. * Associates the vertexData to the passed Mesh.
  36542. * Sets it as updatable or not (default `false`)
  36543. * @param mesh the mesh the vertexData is applied to
  36544. * @param updatable when used and having the value true allows new data to update the vertexData
  36545. * @returns the VertexData
  36546. */
  36547. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36548. this._applyTo(mesh, updatable);
  36549. return this;
  36550. };
  36551. /**
  36552. * Associates the vertexData to the passed Geometry.
  36553. * Sets it as updatable or not (default `false`)
  36554. * @param geometry the geometry the vertexData is applied to
  36555. * @param updatable when used and having the value true allows new data to update the vertexData
  36556. * @returns VertexData
  36557. */
  36558. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36559. this._applyTo(geometry, updatable);
  36560. return this;
  36561. };
  36562. /**
  36563. * Updates the associated mesh
  36564. * @param mesh the mesh to be updated
  36565. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36566. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36567. * @returns VertexData
  36568. */
  36569. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36570. this._update(mesh);
  36571. return this;
  36572. };
  36573. /**
  36574. * Updates the associated geometry
  36575. * @param geometry the geometry to be updated
  36576. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36577. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36578. * @returns VertexData.
  36579. */
  36580. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36581. this._update(geometry);
  36582. return this;
  36583. };
  36584. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36585. if (updatable === void 0) { updatable = false; }
  36586. if (this.positions) {
  36587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36588. }
  36589. if (this.normals) {
  36590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36591. }
  36592. if (this.tangents) {
  36593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36594. }
  36595. if (this.uvs) {
  36596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36597. }
  36598. if (this.uvs2) {
  36599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36600. }
  36601. if (this.uvs3) {
  36602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36603. }
  36604. if (this.uvs4) {
  36605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36606. }
  36607. if (this.uvs5) {
  36608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36609. }
  36610. if (this.uvs6) {
  36611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36612. }
  36613. if (this.colors) {
  36614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36615. }
  36616. if (this.matricesIndices) {
  36617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36618. }
  36619. if (this.matricesWeights) {
  36620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36621. }
  36622. if (this.matricesIndicesExtra) {
  36623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36624. }
  36625. if (this.matricesWeightsExtra) {
  36626. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36627. }
  36628. if (this.indices) {
  36629. meshOrGeometry.setIndices(this.indices, null, updatable);
  36630. }
  36631. else {
  36632. meshOrGeometry.setIndices([], null);
  36633. }
  36634. return this;
  36635. };
  36636. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36637. if (this.positions) {
  36638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36639. }
  36640. if (this.normals) {
  36641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36642. }
  36643. if (this.tangents) {
  36644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36645. }
  36646. if (this.uvs) {
  36647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36648. }
  36649. if (this.uvs2) {
  36650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36651. }
  36652. if (this.uvs3) {
  36653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36654. }
  36655. if (this.uvs4) {
  36656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36657. }
  36658. if (this.uvs5) {
  36659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36660. }
  36661. if (this.uvs6) {
  36662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36663. }
  36664. if (this.colors) {
  36665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36666. }
  36667. if (this.matricesIndices) {
  36668. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36669. }
  36670. if (this.matricesWeights) {
  36671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36672. }
  36673. if (this.matricesIndicesExtra) {
  36674. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36675. }
  36676. if (this.matricesWeightsExtra) {
  36677. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36678. }
  36679. if (this.indices) {
  36680. meshOrGeometry.setIndices(this.indices, null);
  36681. }
  36682. return this;
  36683. };
  36684. /**
  36685. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36686. * @param matrix the transforming matrix
  36687. * @returns the VertexData
  36688. */
  36689. VertexData.prototype.transform = function (matrix) {
  36690. var transformed = BABYLON.Vector3.Zero();
  36691. var index;
  36692. if (this.positions) {
  36693. var position = BABYLON.Vector3.Zero();
  36694. for (index = 0; index < this.positions.length; index += 3) {
  36695. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36696. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36697. this.positions[index] = transformed.x;
  36698. this.positions[index + 1] = transformed.y;
  36699. this.positions[index + 2] = transformed.z;
  36700. }
  36701. }
  36702. if (this.normals) {
  36703. var normal = BABYLON.Vector3.Zero();
  36704. for (index = 0; index < this.normals.length; index += 3) {
  36705. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36706. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36707. this.normals[index] = transformed.x;
  36708. this.normals[index + 1] = transformed.y;
  36709. this.normals[index + 2] = transformed.z;
  36710. }
  36711. }
  36712. if (this.tangents) {
  36713. var tangent = BABYLON.Vector4.Zero();
  36714. var tangentTransformed = BABYLON.Vector4.Zero();
  36715. for (index = 0; index < this.tangents.length; index += 4) {
  36716. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36717. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36718. this.tangents[index] = tangentTransformed.x;
  36719. this.tangents[index + 1] = tangentTransformed.y;
  36720. this.tangents[index + 2] = tangentTransformed.z;
  36721. this.tangents[index + 3] = tangentTransformed.w;
  36722. }
  36723. }
  36724. return this;
  36725. };
  36726. /**
  36727. * Merges the passed VertexData into the current one
  36728. * @param other the VertexData to be merged into the current one
  36729. * @returns the modified VertexData
  36730. */
  36731. VertexData.prototype.merge = function (other) {
  36732. this._validate();
  36733. other._validate();
  36734. if (!this.normals !== !other.normals ||
  36735. !this.tangents !== !other.tangents ||
  36736. !this.uvs !== !other.uvs ||
  36737. !this.uvs2 !== !other.uvs2 ||
  36738. !this.uvs3 !== !other.uvs3 ||
  36739. !this.uvs4 !== !other.uvs4 ||
  36740. !this.uvs5 !== !other.uvs5 ||
  36741. !this.uvs6 !== !other.uvs6 ||
  36742. !this.colors !== !other.colors ||
  36743. !this.matricesIndices !== !other.matricesIndices ||
  36744. !this.matricesWeights !== !other.matricesWeights ||
  36745. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36746. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36747. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36748. }
  36749. if (other.indices) {
  36750. if (!this.indices) {
  36751. this.indices = [];
  36752. }
  36753. var offset = this.positions ? this.positions.length / 3 : 0;
  36754. for (var index = 0; index < other.indices.length; index++) {
  36755. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36756. this.indices.push(other.indices[index] + offset);
  36757. }
  36758. }
  36759. this.positions = this._mergeElement(this.positions, other.positions);
  36760. this.normals = this._mergeElement(this.normals, other.normals);
  36761. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36762. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36763. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36764. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36765. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36766. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36767. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36768. this.colors = this._mergeElement(this.colors, other.colors);
  36769. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36770. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36771. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36772. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36773. return this;
  36774. };
  36775. VertexData.prototype._mergeElement = function (source, other) {
  36776. if (!source) {
  36777. return other;
  36778. }
  36779. if (!other) {
  36780. return source;
  36781. }
  36782. var len = other.length + source.length;
  36783. var isSrcTypedArray = source instanceof Float32Array;
  36784. var isOthTypedArray = other instanceof Float32Array;
  36785. // use non-loop method when the source is Float32Array
  36786. if (isSrcTypedArray) {
  36787. var ret32 = new Float32Array(len);
  36788. ret32.set(source);
  36789. ret32.set(other, source.length);
  36790. return ret32;
  36791. // source is number[], when other is also use concat
  36792. }
  36793. else if (!isOthTypedArray) {
  36794. return source.concat(other);
  36795. // source is a number[], but other is a Float32Array, loop required
  36796. }
  36797. else {
  36798. var ret = source.slice(0); // copy source to a separate array
  36799. for (var i = 0, len = other.length; i < len; i++) {
  36800. ret.push(other[i]);
  36801. }
  36802. return ret;
  36803. }
  36804. };
  36805. VertexData.prototype._validate = function () {
  36806. if (!this.positions) {
  36807. throw new Error("Positions are required");
  36808. }
  36809. var getElementCount = function (kind, values) {
  36810. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36811. if ((values.length % stride) !== 0) {
  36812. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36813. }
  36814. return values.length / stride;
  36815. };
  36816. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36817. var validateElementCount = function (kind, values) {
  36818. var elementCount = getElementCount(kind, values);
  36819. if (elementCount !== positionsElementCount) {
  36820. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36821. }
  36822. };
  36823. if (this.normals)
  36824. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36825. if (this.tangents)
  36826. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36827. if (this.uvs)
  36828. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36829. if (this.uvs2)
  36830. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36831. if (this.uvs3)
  36832. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36833. if (this.uvs4)
  36834. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36835. if (this.uvs5)
  36836. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36837. if (this.uvs6)
  36838. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36839. if (this.colors)
  36840. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36841. if (this.matricesIndices)
  36842. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36843. if (this.matricesWeights)
  36844. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36845. if (this.matricesIndicesExtra)
  36846. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36847. if (this.matricesWeightsExtra)
  36848. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36849. };
  36850. /**
  36851. * Serializes the VertexData
  36852. * @returns a serialized object
  36853. */
  36854. VertexData.prototype.serialize = function () {
  36855. var serializationObject = this.serialize();
  36856. if (this.positions) {
  36857. serializationObject.positions = this.positions;
  36858. }
  36859. if (this.normals) {
  36860. serializationObject.normals = this.normals;
  36861. }
  36862. if (this.tangents) {
  36863. serializationObject.tangents = this.tangents;
  36864. }
  36865. if (this.uvs) {
  36866. serializationObject.uvs = this.uvs;
  36867. }
  36868. if (this.uvs2) {
  36869. serializationObject.uvs2 = this.uvs2;
  36870. }
  36871. if (this.uvs3) {
  36872. serializationObject.uvs3 = this.uvs3;
  36873. }
  36874. if (this.uvs4) {
  36875. serializationObject.uvs4 = this.uvs4;
  36876. }
  36877. if (this.uvs5) {
  36878. serializationObject.uvs5 = this.uvs5;
  36879. }
  36880. if (this.uvs6) {
  36881. serializationObject.uvs6 = this.uvs6;
  36882. }
  36883. if (this.colors) {
  36884. serializationObject.colors = this.colors;
  36885. }
  36886. if (this.matricesIndices) {
  36887. serializationObject.matricesIndices = this.matricesIndices;
  36888. serializationObject.matricesIndices._isExpanded = true;
  36889. }
  36890. if (this.matricesWeights) {
  36891. serializationObject.matricesWeights = this.matricesWeights;
  36892. }
  36893. if (this.matricesIndicesExtra) {
  36894. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36895. serializationObject.matricesIndicesExtra._isExpanded = true;
  36896. }
  36897. if (this.matricesWeightsExtra) {
  36898. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36899. }
  36900. serializationObject.indices = this.indices;
  36901. return serializationObject;
  36902. };
  36903. // Statics
  36904. /**
  36905. * Extracts the vertexData from a mesh
  36906. * @param mesh the mesh from which to extract the VertexData
  36907. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36908. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36909. * @returns the object VertexData associated to the passed mesh
  36910. */
  36911. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36912. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36913. };
  36914. /**
  36915. * Extracts the vertexData from the geometry
  36916. * @param geometry the geometry from which to extract the VertexData
  36917. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36918. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36919. * @returns the object VertexData associated to the passed mesh
  36920. */
  36921. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36922. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36923. };
  36924. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36925. var result = new VertexData();
  36926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36927. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36928. }
  36929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36930. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36931. }
  36932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36933. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36934. }
  36935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36936. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36937. }
  36938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36939. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36940. }
  36941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36942. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36943. }
  36944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36945. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36946. }
  36947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36948. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36949. }
  36950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36951. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36952. }
  36953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36954. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36955. }
  36956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36957. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36958. }
  36959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36960. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36961. }
  36962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36963. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36964. }
  36965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36966. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36967. }
  36968. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36969. return result;
  36970. };
  36971. /**
  36972. * Creates the VertexData for a Ribbon
  36973. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36974. * * pathArray array of paths, each of which an array of successive Vector3
  36975. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36976. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36977. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36978. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36979. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36980. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36981. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36982. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36983. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36984. * @returns the VertexData of the ribbon
  36985. */
  36986. VertexData.CreateRibbon = function (options) {
  36987. var pathArray = options.pathArray;
  36988. var closeArray = options.closeArray || false;
  36989. var closePath = options.closePath || false;
  36990. var invertUV = options.invertUV || false;
  36991. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36992. var offset = options.offset || defaultOffset;
  36993. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36994. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36995. var customUV = options.uvs;
  36996. var customColors = options.colors;
  36997. var positions = [];
  36998. var indices = [];
  36999. var normals = [];
  37000. var uvs = [];
  37001. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37002. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37003. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37004. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37005. var minlg; // minimal length among all paths from pathArray
  37006. var lg = []; // array of path lengths : nb of vertex per path
  37007. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37008. var p; // path iterator
  37009. var i; // point iterator
  37010. var j; // point iterator
  37011. // if single path in pathArray
  37012. if (pathArray.length < 2) {
  37013. var ar1 = [];
  37014. var ar2 = [];
  37015. for (i = 0; i < pathArray[0].length - offset; i++) {
  37016. ar1.push(pathArray[0][i]);
  37017. ar2.push(pathArray[0][i + offset]);
  37018. }
  37019. pathArray = [ar1, ar2];
  37020. }
  37021. // positions and horizontal distances (u)
  37022. var idc = 0;
  37023. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37024. var path;
  37025. var l;
  37026. minlg = pathArray[0].length;
  37027. var vectlg;
  37028. var dist;
  37029. for (p = 0; p < pathArray.length; p++) {
  37030. uTotalDistance[p] = 0;
  37031. us[p] = [0];
  37032. path = pathArray[p];
  37033. l = path.length;
  37034. minlg = (minlg < l) ? minlg : l;
  37035. j = 0;
  37036. while (j < l) {
  37037. positions.push(path[j].x, path[j].y, path[j].z);
  37038. if (j > 0) {
  37039. vectlg = path[j].subtract(path[j - 1]).length();
  37040. dist = vectlg + uTotalDistance[p];
  37041. us[p].push(dist);
  37042. uTotalDistance[p] = dist;
  37043. }
  37044. j++;
  37045. }
  37046. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37047. j--;
  37048. positions.push(path[0].x, path[0].y, path[0].z);
  37049. vectlg = path[j].subtract(path[0]).length();
  37050. dist = vectlg + uTotalDistance[p];
  37051. us[p].push(dist);
  37052. uTotalDistance[p] = dist;
  37053. }
  37054. lg[p] = l + closePathCorr;
  37055. idx[p] = idc;
  37056. idc += (l + closePathCorr);
  37057. }
  37058. // vertical distances (v)
  37059. var path1;
  37060. var path2;
  37061. var vertex1 = null;
  37062. var vertex2 = null;
  37063. for (i = 0; i < minlg + closePathCorr; i++) {
  37064. vTotalDistance[i] = 0;
  37065. vs[i] = [0];
  37066. for (p = 0; p < pathArray.length - 1; p++) {
  37067. path1 = pathArray[p];
  37068. path2 = pathArray[p + 1];
  37069. if (i === minlg) { // closePath
  37070. vertex1 = path1[0];
  37071. vertex2 = path2[0];
  37072. }
  37073. else {
  37074. vertex1 = path1[i];
  37075. vertex2 = path2[i];
  37076. }
  37077. vectlg = vertex2.subtract(vertex1).length();
  37078. dist = vectlg + vTotalDistance[i];
  37079. vs[i].push(dist);
  37080. vTotalDistance[i] = dist;
  37081. }
  37082. if (closeArray && vertex2 && vertex1) {
  37083. path1 = pathArray[p];
  37084. path2 = pathArray[0];
  37085. if (i === minlg) { // closePath
  37086. vertex2 = path2[0];
  37087. }
  37088. vectlg = vertex2.subtract(vertex1).length();
  37089. dist = vectlg + vTotalDistance[i];
  37090. vTotalDistance[i] = dist;
  37091. }
  37092. }
  37093. // uvs
  37094. var u;
  37095. var v;
  37096. if (customUV) {
  37097. for (p = 0; p < customUV.length; p++) {
  37098. uvs.push(customUV[p].x, customUV[p].y);
  37099. }
  37100. }
  37101. else {
  37102. for (p = 0; p < pathArray.length; p++) {
  37103. for (i = 0; i < minlg + closePathCorr; i++) {
  37104. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37105. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37106. if (invertUV) {
  37107. uvs.push(v, u);
  37108. }
  37109. else {
  37110. uvs.push(u, v);
  37111. }
  37112. }
  37113. }
  37114. }
  37115. // indices
  37116. p = 0; // path index
  37117. var pi = 0; // positions array index
  37118. var l1 = lg[p] - 1; // path1 length
  37119. var l2 = lg[p + 1] - 1; // path2 length
  37120. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37121. var shft = idx[1] - idx[0]; // shift
  37122. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37123. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37124. // 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
  37125. indices.push(pi, pi + shft, pi + 1);
  37126. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37127. pi += 1;
  37128. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37129. p++;
  37130. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37131. shft = idx[0] - idx[p];
  37132. l1 = lg[p] - 1;
  37133. l2 = lg[0] - 1;
  37134. }
  37135. else {
  37136. shft = idx[p + 1] - idx[p];
  37137. l1 = lg[p] - 1;
  37138. l2 = lg[p + 1] - 1;
  37139. }
  37140. pi = idx[p];
  37141. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37142. }
  37143. }
  37144. // normals
  37145. VertexData.ComputeNormals(positions, indices, normals);
  37146. if (closePath) { // update both the first and last vertex normals to their average value
  37147. var indexFirst = 0;
  37148. var indexLast = 0;
  37149. for (p = 0; p < pathArray.length; p++) {
  37150. indexFirst = idx[p] * 3;
  37151. if (p + 1 < pathArray.length) {
  37152. indexLast = (idx[p + 1] - 1) * 3;
  37153. }
  37154. else {
  37155. indexLast = normals.length - 3;
  37156. }
  37157. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37158. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37159. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37160. normals[indexLast] = normals[indexFirst];
  37161. normals[indexLast + 1] = normals[indexFirst + 1];
  37162. normals[indexLast + 2] = normals[indexFirst + 2];
  37163. }
  37164. }
  37165. // sides
  37166. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37167. // Colors
  37168. var colors = null;
  37169. if (customColors) {
  37170. colors = new Float32Array(customColors.length * 4);
  37171. for (var c = 0; c < customColors.length; c++) {
  37172. colors[c * 4] = customColors[c].r;
  37173. colors[c * 4 + 1] = customColors[c].g;
  37174. colors[c * 4 + 2] = customColors[c].b;
  37175. colors[c * 4 + 3] = customColors[c].a;
  37176. }
  37177. }
  37178. // Result
  37179. var vertexData = new VertexData();
  37180. var positions32 = new Float32Array(positions);
  37181. var normals32 = new Float32Array(normals);
  37182. var uvs32 = new Float32Array(uvs);
  37183. vertexData.indices = indices;
  37184. vertexData.positions = positions32;
  37185. vertexData.normals = normals32;
  37186. vertexData.uvs = uvs32;
  37187. if (colors) {
  37188. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37189. }
  37190. if (closePath) {
  37191. vertexData._idx = idx;
  37192. }
  37193. return vertexData;
  37194. };
  37195. /**
  37196. * Creates the VertexData for a box
  37197. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37198. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37199. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37200. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37201. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37202. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37203. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37204. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37205. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37206. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37207. * @returns the VertexData of the box
  37208. */
  37209. VertexData.CreateBox = function (options) {
  37210. var normalsSource = [
  37211. new BABYLON.Vector3(0, 0, 1),
  37212. new BABYLON.Vector3(0, 0, -1),
  37213. new BABYLON.Vector3(1, 0, 0),
  37214. new BABYLON.Vector3(-1, 0, 0),
  37215. new BABYLON.Vector3(0, 1, 0),
  37216. new BABYLON.Vector3(0, -1, 0)
  37217. ];
  37218. var indices = [];
  37219. var positions = [];
  37220. var normals = [];
  37221. var uvs = [];
  37222. var width = options.width || options.size || 1;
  37223. var height = options.height || options.size || 1;
  37224. var depth = options.depth || options.size || 1;
  37225. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37226. var faceUV = options.faceUV || new Array(6);
  37227. var faceColors = options.faceColors;
  37228. var colors = [];
  37229. // default face colors and UV if undefined
  37230. for (var f = 0; f < 6; f++) {
  37231. if (faceUV[f] === undefined) {
  37232. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37233. }
  37234. if (faceColors && faceColors[f] === undefined) {
  37235. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37236. }
  37237. }
  37238. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37239. // Create each face in turn.
  37240. for (var index = 0; index < normalsSource.length; index++) {
  37241. var normal = normalsSource[index];
  37242. // Get two vectors perpendicular to the face normal and to each other.
  37243. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37244. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37245. // Six indices (two triangles) per face.
  37246. var verticesLength = positions.length / 3;
  37247. indices.push(verticesLength);
  37248. indices.push(verticesLength + 1);
  37249. indices.push(verticesLength + 2);
  37250. indices.push(verticesLength);
  37251. indices.push(verticesLength + 2);
  37252. indices.push(verticesLength + 3);
  37253. // Four vertices per face.
  37254. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37255. positions.push(vertex.x, vertex.y, vertex.z);
  37256. normals.push(normal.x, normal.y, normal.z);
  37257. uvs.push(faceUV[index].z, faceUV[index].w);
  37258. if (faceColors) {
  37259. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37260. }
  37261. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37262. positions.push(vertex.x, vertex.y, vertex.z);
  37263. normals.push(normal.x, normal.y, normal.z);
  37264. uvs.push(faceUV[index].x, faceUV[index].w);
  37265. if (faceColors) {
  37266. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37267. }
  37268. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37269. positions.push(vertex.x, vertex.y, vertex.z);
  37270. normals.push(normal.x, normal.y, normal.z);
  37271. uvs.push(faceUV[index].x, faceUV[index].y);
  37272. if (faceColors) {
  37273. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37274. }
  37275. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37276. positions.push(vertex.x, vertex.y, vertex.z);
  37277. normals.push(normal.x, normal.y, normal.z);
  37278. uvs.push(faceUV[index].z, faceUV[index].y);
  37279. if (faceColors) {
  37280. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37281. }
  37282. }
  37283. // sides
  37284. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37285. // Result
  37286. var vertexData = new VertexData();
  37287. vertexData.indices = indices;
  37288. vertexData.positions = positions;
  37289. vertexData.normals = normals;
  37290. vertexData.uvs = uvs;
  37291. if (faceColors) {
  37292. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37293. vertexData.colors = totalColors;
  37294. }
  37295. return vertexData;
  37296. };
  37297. /**
  37298. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37299. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37300. * * segments sets the number of horizontal strips optional, default 32
  37301. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37302. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37303. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37304. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37305. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37306. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37307. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37308. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37309. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37310. * @returns the VertexData of the ellipsoid
  37311. */
  37312. VertexData.CreateSphere = function (options) {
  37313. var segments = options.segments || 32;
  37314. var diameterX = options.diameterX || options.diameter || 1;
  37315. var diameterY = options.diameterY || options.diameter || 1;
  37316. var diameterZ = options.diameterZ || options.diameter || 1;
  37317. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37318. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37319. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37320. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37321. var totalZRotationSteps = 2 + segments;
  37322. var totalYRotationSteps = 2 * totalZRotationSteps;
  37323. var indices = [];
  37324. var positions = [];
  37325. var normals = [];
  37326. var uvs = [];
  37327. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37328. var normalizedZ = zRotationStep / totalZRotationSteps;
  37329. var angleZ = normalizedZ * Math.PI * slice;
  37330. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37331. var normalizedY = yRotationStep / totalYRotationSteps;
  37332. var angleY = normalizedY * Math.PI * 2 * arc;
  37333. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37334. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37335. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37336. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37337. var vertex = complete.multiply(radius);
  37338. var normal = complete.divide(radius).normalize();
  37339. positions.push(vertex.x, vertex.y, vertex.z);
  37340. normals.push(normal.x, normal.y, normal.z);
  37341. uvs.push(normalizedY, normalizedZ);
  37342. }
  37343. if (zRotationStep > 0) {
  37344. var verticesCount = positions.length / 3;
  37345. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37346. indices.push((firstIndex));
  37347. indices.push((firstIndex + 1));
  37348. indices.push(firstIndex + totalYRotationSteps + 1);
  37349. indices.push((firstIndex + totalYRotationSteps + 1));
  37350. indices.push((firstIndex + 1));
  37351. indices.push((firstIndex + totalYRotationSteps + 2));
  37352. }
  37353. }
  37354. }
  37355. // Sides
  37356. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37357. // Result
  37358. var vertexData = new VertexData();
  37359. vertexData.indices = indices;
  37360. vertexData.positions = positions;
  37361. vertexData.normals = normals;
  37362. vertexData.uvs = uvs;
  37363. return vertexData;
  37364. };
  37365. /**
  37366. * Creates the VertexData for a cylinder, cone or prism
  37367. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37368. * * height sets the height (y direction) of the cylinder, optional, default 2
  37369. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37370. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37371. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37372. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37373. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37374. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37375. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37376. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37377. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37378. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37379. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37380. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37381. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37382. * @returns the VertexData of the cylinder, cone or prism
  37383. */
  37384. VertexData.CreateCylinder = function (options) {
  37385. var height = options.height || 2;
  37386. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37387. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37388. var tessellation = options.tessellation || 24;
  37389. var subdivisions = options.subdivisions || 1;
  37390. var hasRings = options.hasRings ? true : false;
  37391. var enclose = options.enclose ? true : false;
  37392. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37393. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37394. var faceUV = options.faceUV || new Array(3);
  37395. var faceColors = options.faceColors;
  37396. // default face colors and UV if undefined
  37397. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37398. var ringNb = (hasRings) ? subdivisions : 1;
  37399. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37400. var f;
  37401. for (f = 0; f < surfaceNb; f++) {
  37402. if (faceColors && faceColors[f] === undefined) {
  37403. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37404. }
  37405. }
  37406. for (f = 0; f < surfaceNb; f++) {
  37407. if (faceUV && faceUV[f] === undefined) {
  37408. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37409. }
  37410. }
  37411. var indices = new Array();
  37412. var positions = new Array();
  37413. var normals = new Array();
  37414. var uvs = new Array();
  37415. var colors = new Array();
  37416. var angle_step = Math.PI * 2 * arc / tessellation;
  37417. var angle;
  37418. var h;
  37419. var radius;
  37420. var tan = (diameterBottom - diameterTop) / 2 / height;
  37421. var ringVertex = BABYLON.Vector3.Zero();
  37422. var ringNormal = BABYLON.Vector3.Zero();
  37423. var ringFirstVertex = BABYLON.Vector3.Zero();
  37424. var ringFirstNormal = BABYLON.Vector3.Zero();
  37425. var quadNormal = BABYLON.Vector3.Zero();
  37426. var Y = BABYLON.Axis.Y;
  37427. // positions, normals, uvs
  37428. var i;
  37429. var j;
  37430. var r;
  37431. var ringIdx = 1;
  37432. var s = 1; // surface index
  37433. var cs = 0;
  37434. var v = 0;
  37435. for (i = 0; i <= subdivisions; i++) {
  37436. h = i / subdivisions;
  37437. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37438. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37439. for (r = 0; r < ringIdx; r++) {
  37440. if (hasRings) {
  37441. s += r;
  37442. }
  37443. if (enclose) {
  37444. s += 2 * r;
  37445. }
  37446. for (j = 0; j <= tessellation; j++) {
  37447. angle = j * angle_step;
  37448. // position
  37449. ringVertex.x = Math.cos(-angle) * radius;
  37450. ringVertex.y = -height / 2 + h * height;
  37451. ringVertex.z = Math.sin(-angle) * radius;
  37452. // normal
  37453. if (diameterTop === 0 && i === subdivisions) {
  37454. // if no top cap, reuse former normals
  37455. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37456. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37457. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37458. }
  37459. else {
  37460. ringNormal.x = ringVertex.x;
  37461. ringNormal.z = ringVertex.z;
  37462. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37463. ringNormal.normalize();
  37464. }
  37465. // keep first ring vertex values for enclose
  37466. if (j === 0) {
  37467. ringFirstVertex.copyFrom(ringVertex);
  37468. ringFirstNormal.copyFrom(ringNormal);
  37469. }
  37470. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37471. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37472. if (hasRings) {
  37473. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37474. }
  37475. else {
  37476. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37477. }
  37478. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37479. if (faceColors) {
  37480. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37481. }
  37482. }
  37483. // if enclose, add four vertices and their dedicated normals
  37484. if (arc !== 1 && enclose) {
  37485. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37486. positions.push(0, ringVertex.y, 0);
  37487. positions.push(0, ringVertex.y, 0);
  37488. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37489. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37490. quadNormal.normalize();
  37491. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37492. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37493. quadNormal.normalize();
  37494. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37495. if (hasRings) {
  37496. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37497. }
  37498. else {
  37499. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37500. }
  37501. uvs.push(faceUV[s + 1].x, v);
  37502. uvs.push(faceUV[s + 1].z, v);
  37503. if (hasRings) {
  37504. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37505. }
  37506. else {
  37507. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37508. }
  37509. uvs.push(faceUV[s + 2].x, v);
  37510. uvs.push(faceUV[s + 2].z, v);
  37511. if (faceColors) {
  37512. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37513. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37514. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37515. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37516. }
  37517. }
  37518. if (cs !== s) {
  37519. cs = s;
  37520. }
  37521. }
  37522. }
  37523. // indices
  37524. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37525. var s;
  37526. i = 0;
  37527. for (s = 0; s < subdivisions; s++) {
  37528. var i0 = 0;
  37529. var i1 = 0;
  37530. var i2 = 0;
  37531. var i3 = 0;
  37532. for (j = 0; j < tessellation; j++) {
  37533. i0 = i * (e + 1) + j;
  37534. i1 = (i + 1) * (e + 1) + j;
  37535. i2 = i * (e + 1) + (j + 1);
  37536. i3 = (i + 1) * (e + 1) + (j + 1);
  37537. indices.push(i0, i1, i2);
  37538. indices.push(i3, i2, i1);
  37539. }
  37540. if (arc !== 1 && enclose) { // if enclose, add two quads
  37541. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37542. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37543. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37544. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37545. }
  37546. i = (hasRings) ? (i + 2) : (i + 1);
  37547. }
  37548. // Caps
  37549. var createCylinderCap = function (isTop) {
  37550. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37551. if (radius === 0) {
  37552. return;
  37553. }
  37554. // Cap positions, normals & uvs
  37555. var angle;
  37556. var circleVector;
  37557. var i;
  37558. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37559. var c = null;
  37560. if (faceColors) {
  37561. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37562. }
  37563. // cap center
  37564. var vbase = positions.length / 3;
  37565. var offset = isTop ? height / 2 : -height / 2;
  37566. var center = new BABYLON.Vector3(0, offset, 0);
  37567. positions.push(center.x, center.y, center.z);
  37568. normals.push(0, isTop ? 1 : -1, 0);
  37569. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37570. if (c) {
  37571. colors.push(c.r, c.g, c.b, c.a);
  37572. }
  37573. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37574. for (i = 0; i <= tessellation; i++) {
  37575. angle = Math.PI * 2 * i * arc / tessellation;
  37576. var cos = Math.cos(-angle);
  37577. var sin = Math.sin(-angle);
  37578. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37579. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37580. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37581. normals.push(0, isTop ? 1 : -1, 0);
  37582. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37583. if (c) {
  37584. colors.push(c.r, c.g, c.b, c.a);
  37585. }
  37586. }
  37587. // Cap indices
  37588. for (i = 0; i < tessellation; i++) {
  37589. if (!isTop) {
  37590. indices.push(vbase);
  37591. indices.push(vbase + (i + 1));
  37592. indices.push(vbase + (i + 2));
  37593. }
  37594. else {
  37595. indices.push(vbase);
  37596. indices.push(vbase + (i + 2));
  37597. indices.push(vbase + (i + 1));
  37598. }
  37599. }
  37600. };
  37601. // add caps to geometry
  37602. createCylinderCap(false);
  37603. createCylinderCap(true);
  37604. // Sides
  37605. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37606. var vertexData = new VertexData();
  37607. vertexData.indices = indices;
  37608. vertexData.positions = positions;
  37609. vertexData.normals = normals;
  37610. vertexData.uvs = uvs;
  37611. if (faceColors) {
  37612. vertexData.colors = colors;
  37613. }
  37614. return vertexData;
  37615. };
  37616. /**
  37617. * Creates the VertexData for a torus
  37618. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37619. * * diameter the diameter of the torus, optional default 1
  37620. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37621. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37622. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37623. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37624. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37625. * @returns the VertexData of the torus
  37626. */
  37627. VertexData.CreateTorus = function (options) {
  37628. var indices = [];
  37629. var positions = [];
  37630. var normals = [];
  37631. var uvs = [];
  37632. var diameter = options.diameter || 1;
  37633. var thickness = options.thickness || 0.5;
  37634. var tessellation = options.tessellation || 16;
  37635. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37636. var stride = tessellation + 1;
  37637. for (var i = 0; i <= tessellation; i++) {
  37638. var u = i / tessellation;
  37639. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37640. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37641. for (var j = 0; j <= tessellation; j++) {
  37642. var v = 1 - j / tessellation;
  37643. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37644. var dx = Math.cos(innerAngle);
  37645. var dy = Math.sin(innerAngle);
  37646. // Create a vertex.
  37647. var normal = new BABYLON.Vector3(dx, dy, 0);
  37648. var position = normal.scale(thickness / 2);
  37649. var textureCoordinate = new BABYLON.Vector2(u, v);
  37650. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37651. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37652. positions.push(position.x, position.y, position.z);
  37653. normals.push(normal.x, normal.y, normal.z);
  37654. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37655. // And create indices for two triangles.
  37656. var nextI = (i + 1) % stride;
  37657. var nextJ = (j + 1) % stride;
  37658. indices.push(i * stride + j);
  37659. indices.push(i * stride + nextJ);
  37660. indices.push(nextI * stride + j);
  37661. indices.push(i * stride + nextJ);
  37662. indices.push(nextI * stride + nextJ);
  37663. indices.push(nextI * stride + j);
  37664. }
  37665. }
  37666. // Sides
  37667. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37668. // Result
  37669. var vertexData = new VertexData();
  37670. vertexData.indices = indices;
  37671. vertexData.positions = positions;
  37672. vertexData.normals = normals;
  37673. vertexData.uvs = uvs;
  37674. return vertexData;
  37675. };
  37676. /**
  37677. * Creates the VertexData of the LineSystem
  37678. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37679. * - lines an array of lines, each line being an array of successive Vector3
  37680. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37681. * @returns the VertexData of the LineSystem
  37682. */
  37683. VertexData.CreateLineSystem = function (options) {
  37684. var indices = [];
  37685. var positions = [];
  37686. var lines = options.lines;
  37687. var colors = options.colors;
  37688. var vertexColors = [];
  37689. var idx = 0;
  37690. for (var l = 0; l < lines.length; l++) {
  37691. var points = lines[l];
  37692. for (var index = 0; index < points.length; index++) {
  37693. positions.push(points[index].x, points[index].y, points[index].z);
  37694. if (colors) {
  37695. var color = colors[l];
  37696. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37697. }
  37698. if (index > 0) {
  37699. indices.push(idx - 1);
  37700. indices.push(idx);
  37701. }
  37702. idx++;
  37703. }
  37704. }
  37705. var vertexData = new VertexData();
  37706. vertexData.indices = indices;
  37707. vertexData.positions = positions;
  37708. if (colors) {
  37709. vertexData.colors = vertexColors;
  37710. }
  37711. return vertexData;
  37712. };
  37713. /**
  37714. * Create the VertexData for a DashedLines
  37715. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37716. * - points an array successive Vector3
  37717. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37718. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37719. * - dashNb the intended total number of dashes, optional, default 200
  37720. * @returns the VertexData for the DashedLines
  37721. */
  37722. VertexData.CreateDashedLines = function (options) {
  37723. var dashSize = options.dashSize || 3;
  37724. var gapSize = options.gapSize || 1;
  37725. var dashNb = options.dashNb || 200;
  37726. var points = options.points;
  37727. var positions = new Array();
  37728. var indices = new Array();
  37729. var curvect = BABYLON.Vector3.Zero();
  37730. var lg = 0;
  37731. var nb = 0;
  37732. var shft = 0;
  37733. var dashshft = 0;
  37734. var curshft = 0;
  37735. var idx = 0;
  37736. var i = 0;
  37737. for (i = 0; i < points.length - 1; i++) {
  37738. points[i + 1].subtractToRef(points[i], curvect);
  37739. lg += curvect.length();
  37740. }
  37741. shft = lg / dashNb;
  37742. dashshft = dashSize * shft / (dashSize + gapSize);
  37743. for (i = 0; i < points.length - 1; i++) {
  37744. points[i + 1].subtractToRef(points[i], curvect);
  37745. nb = Math.floor(curvect.length() / shft);
  37746. curvect.normalize();
  37747. for (var j = 0; j < nb; j++) {
  37748. curshft = shft * j;
  37749. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37750. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37751. indices.push(idx, idx + 1);
  37752. idx += 2;
  37753. }
  37754. }
  37755. // Result
  37756. var vertexData = new VertexData();
  37757. vertexData.positions = positions;
  37758. vertexData.indices = indices;
  37759. return vertexData;
  37760. };
  37761. /**
  37762. * Creates the VertexData for a Ground
  37763. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37764. * - width the width (x direction) of the ground, optional, default 1
  37765. * - height the height (z direction) of the ground, optional, default 1
  37766. * - subdivisions the number of subdivisions per side, optional, default 1
  37767. * @returns the VertexData of the Ground
  37768. */
  37769. VertexData.CreateGround = function (options) {
  37770. var indices = [];
  37771. var positions = [];
  37772. var normals = [];
  37773. var uvs = [];
  37774. var row, col;
  37775. var width = options.width || 1;
  37776. var height = options.height || 1;
  37777. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37778. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37779. for (row = 0; row <= subdivisionsY; row++) {
  37780. for (col = 0; col <= subdivisionsX; col++) {
  37781. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37782. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37783. positions.push(position.x, position.y, position.z);
  37784. normals.push(normal.x, normal.y, normal.z);
  37785. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37786. }
  37787. }
  37788. for (row = 0; row < subdivisionsY; row++) {
  37789. for (col = 0; col < subdivisionsX; col++) {
  37790. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37791. indices.push(col + 1 + row * (subdivisionsX + 1));
  37792. indices.push(col + row * (subdivisionsX + 1));
  37793. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37794. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37795. indices.push(col + row * (subdivisionsX + 1));
  37796. }
  37797. }
  37798. // Result
  37799. var vertexData = new VertexData();
  37800. vertexData.indices = indices;
  37801. vertexData.positions = positions;
  37802. vertexData.normals = normals;
  37803. vertexData.uvs = uvs;
  37804. return vertexData;
  37805. };
  37806. /**
  37807. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37808. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37809. * * xmin the ground minimum X coordinate, optional, default -1
  37810. * * zmin the ground minimum Z coordinate, optional, default -1
  37811. * * xmax the ground maximum X coordinate, optional, default 1
  37812. * * zmax the ground maximum Z coordinate, optional, default 1
  37813. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37814. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37815. * @returns the VertexData of the TiledGround
  37816. */
  37817. VertexData.CreateTiledGround = function (options) {
  37818. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37819. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37820. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37821. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37822. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37823. var precision = options.precision || { w: 1, h: 1 };
  37824. var indices = new Array();
  37825. var positions = new Array();
  37826. var normals = new Array();
  37827. var uvs = new Array();
  37828. var row, col, tileRow, tileCol;
  37829. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37830. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37831. precision.w = (precision.w < 1) ? 1 : precision.w;
  37832. precision.h = (precision.h < 1) ? 1 : precision.h;
  37833. var tileSize = {
  37834. 'w': (xmax - xmin) / subdivisions.w,
  37835. 'h': (zmax - zmin) / subdivisions.h
  37836. };
  37837. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37838. // Indices
  37839. var base = positions.length / 3;
  37840. var rowLength = precision.w + 1;
  37841. for (row = 0; row < precision.h; row++) {
  37842. for (col = 0; col < precision.w; col++) {
  37843. var square = [
  37844. base + col + row * rowLength,
  37845. base + (col + 1) + row * rowLength,
  37846. base + (col + 1) + (row + 1) * rowLength,
  37847. base + col + (row + 1) * rowLength
  37848. ];
  37849. indices.push(square[1]);
  37850. indices.push(square[2]);
  37851. indices.push(square[3]);
  37852. indices.push(square[0]);
  37853. indices.push(square[1]);
  37854. indices.push(square[3]);
  37855. }
  37856. }
  37857. // Position, normals and uvs
  37858. var position = BABYLON.Vector3.Zero();
  37859. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37860. for (row = 0; row <= precision.h; row++) {
  37861. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37862. for (col = 0; col <= precision.w; col++) {
  37863. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37864. position.y = 0;
  37865. positions.push(position.x, position.y, position.z);
  37866. normals.push(normal.x, normal.y, normal.z);
  37867. uvs.push(col / precision.w, row / precision.h);
  37868. }
  37869. }
  37870. }
  37871. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37872. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37873. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37874. }
  37875. }
  37876. // Result
  37877. var vertexData = new VertexData();
  37878. vertexData.indices = indices;
  37879. vertexData.positions = positions;
  37880. vertexData.normals = normals;
  37881. vertexData.uvs = uvs;
  37882. return vertexData;
  37883. };
  37884. /**
  37885. * Creates the VertexData of the Ground designed from a heightmap
  37886. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37887. * * width the width (x direction) of the ground
  37888. * * height the height (z direction) of the ground
  37889. * * subdivisions the number of subdivisions per side
  37890. * * minHeight the minimum altitude on the ground, optional, default 0
  37891. * * maxHeight the maximum altitude on the ground, optional default 1
  37892. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37893. * * buffer the array holding the image color data
  37894. * * bufferWidth the width of image
  37895. * * bufferHeight the height of image
  37896. * @returns the VertexData of the Ground designed from a heightmap
  37897. */
  37898. VertexData.CreateGroundFromHeightMap = function (options) {
  37899. var indices = [];
  37900. var positions = [];
  37901. var normals = [];
  37902. var uvs = [];
  37903. var row, col;
  37904. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37905. // Vertices
  37906. for (row = 0; row <= options.subdivisions; row++) {
  37907. for (col = 0; col <= options.subdivisions; col++) {
  37908. 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));
  37909. // Compute height
  37910. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37911. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37912. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37913. var r = options.buffer[pos] / 255.0;
  37914. var g = options.buffer[pos + 1] / 255.0;
  37915. var b = options.buffer[pos + 2] / 255.0;
  37916. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37917. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37918. // Add vertex
  37919. positions.push(position.x, position.y, position.z);
  37920. normals.push(0, 0, 0);
  37921. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37922. }
  37923. }
  37924. // Indices
  37925. for (row = 0; row < options.subdivisions; row++) {
  37926. for (col = 0; col < options.subdivisions; col++) {
  37927. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37928. indices.push(col + 1 + row * (options.subdivisions + 1));
  37929. indices.push(col + row * (options.subdivisions + 1));
  37930. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37931. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37932. indices.push(col + row * (options.subdivisions + 1));
  37933. }
  37934. }
  37935. // Normals
  37936. VertexData.ComputeNormals(positions, indices, normals);
  37937. // Result
  37938. var vertexData = new VertexData();
  37939. vertexData.indices = indices;
  37940. vertexData.positions = positions;
  37941. vertexData.normals = normals;
  37942. vertexData.uvs = uvs;
  37943. return vertexData;
  37944. };
  37945. /**
  37946. * Creates the VertexData for a Plane
  37947. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37948. * * size sets the width and height of the plane to the value of size, optional default 1
  37949. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37950. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37951. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37952. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37953. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37954. * @returns the VertexData of the box
  37955. */
  37956. VertexData.CreatePlane = function (options) {
  37957. var indices = [];
  37958. var positions = [];
  37959. var normals = [];
  37960. var uvs = [];
  37961. var width = options.width || options.size || 1;
  37962. var height = options.height || options.size || 1;
  37963. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37964. // Vertices
  37965. var halfWidth = width / 2.0;
  37966. var halfHeight = height / 2.0;
  37967. positions.push(-halfWidth, -halfHeight, 0);
  37968. normals.push(0, 0, -1.0);
  37969. uvs.push(0.0, 0.0);
  37970. positions.push(halfWidth, -halfHeight, 0);
  37971. normals.push(0, 0, -1.0);
  37972. uvs.push(1.0, 0.0);
  37973. positions.push(halfWidth, halfHeight, 0);
  37974. normals.push(0, 0, -1.0);
  37975. uvs.push(1.0, 1.0);
  37976. positions.push(-halfWidth, halfHeight, 0);
  37977. normals.push(0, 0, -1.0);
  37978. uvs.push(0.0, 1.0);
  37979. // Indices
  37980. indices.push(0);
  37981. indices.push(1);
  37982. indices.push(2);
  37983. indices.push(0);
  37984. indices.push(2);
  37985. indices.push(3);
  37986. // Sides
  37987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37988. // Result
  37989. var vertexData = new VertexData();
  37990. vertexData.indices = indices;
  37991. vertexData.positions = positions;
  37992. vertexData.normals = normals;
  37993. vertexData.uvs = uvs;
  37994. return vertexData;
  37995. };
  37996. /**
  37997. * Creates the VertexData of the Disc or regular Polygon
  37998. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37999. * * radius the radius of the disc, optional default 0.5
  38000. * * tessellation the number of polygon sides, optional, default 64
  38001. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  38002. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38003. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38004. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38005. * @returns the VertexData of the box
  38006. */
  38007. VertexData.CreateDisc = function (options) {
  38008. var positions = new Array();
  38009. var indices = new Array();
  38010. var normals = new Array();
  38011. var uvs = new Array();
  38012. var radius = options.radius || 0.5;
  38013. var tessellation = options.tessellation || 64;
  38014. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38015. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38016. // positions and uvs
  38017. positions.push(0, 0, 0); // disc center first
  38018. uvs.push(0.5, 0.5);
  38019. var theta = Math.PI * 2 * arc;
  38020. var step = theta / tessellation;
  38021. for (var a = 0; a < theta; a += step) {
  38022. var x = Math.cos(a);
  38023. var y = Math.sin(a);
  38024. var u = (x + 1) / 2;
  38025. var v = (1 - y) / 2;
  38026. positions.push(radius * x, radius * y, 0);
  38027. uvs.push(u, v);
  38028. }
  38029. if (arc === 1) {
  38030. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38031. uvs.push(uvs[2], uvs[3]);
  38032. }
  38033. //indices
  38034. var vertexNb = positions.length / 3;
  38035. for (var i = 1; i < vertexNb - 1; i++) {
  38036. indices.push(i + 1, 0, i);
  38037. }
  38038. // result
  38039. VertexData.ComputeNormals(positions, indices, normals);
  38040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38041. var vertexData = new VertexData();
  38042. vertexData.indices = indices;
  38043. vertexData.positions = positions;
  38044. vertexData.normals = normals;
  38045. vertexData.uvs = uvs;
  38046. return vertexData;
  38047. };
  38048. /**
  38049. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38050. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38051. * @param polygon a mesh built from polygonTriangulation.build()
  38052. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38053. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38054. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38055. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38056. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38057. * @returns the VertexData of the Polygon
  38058. */
  38059. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38060. var faceUV = fUV || new Array(3);
  38061. var faceColors = fColors;
  38062. var colors = [];
  38063. // default face colors and UV if undefined
  38064. for (var f = 0; f < 3; f++) {
  38065. if (faceUV[f] === undefined) {
  38066. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38067. }
  38068. if (faceColors && faceColors[f] === undefined) {
  38069. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38070. }
  38071. }
  38072. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38073. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38074. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38075. var indices = polygon.getIndices();
  38076. // set face colours and textures
  38077. var idx = 0;
  38078. var face = 0;
  38079. for (var index = 0; index < normals.length; index += 3) {
  38080. //Edge Face no. 1
  38081. if (Math.abs(normals[index + 1]) < 0.001) {
  38082. face = 1;
  38083. }
  38084. //Top Face no. 0
  38085. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38086. face = 0;
  38087. }
  38088. //Bottom Face no. 2
  38089. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38090. face = 2;
  38091. }
  38092. idx = index / 3;
  38093. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38094. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38095. if (faceColors) {
  38096. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38097. }
  38098. }
  38099. // sides
  38100. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38101. // Result
  38102. var vertexData = new VertexData();
  38103. vertexData.indices = indices;
  38104. vertexData.positions = positions;
  38105. vertexData.normals = normals;
  38106. vertexData.uvs = uvs;
  38107. if (faceColors) {
  38108. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38109. vertexData.colors = totalColors;
  38110. }
  38111. return vertexData;
  38112. };
  38113. /**
  38114. * Creates the VertexData of the IcoSphere
  38115. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38116. * * radius the radius of the IcoSphere, optional default 1
  38117. * * radiusX allows stretching in the x direction, optional, default radius
  38118. * * radiusY allows stretching in the y direction, optional, default radius
  38119. * * radiusZ allows stretching in the z direction, optional, default radius
  38120. * * flat when true creates a flat shaded mesh, optional, default true
  38121. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38122. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38123. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38124. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38125. * @returns the VertexData of the IcoSphere
  38126. */
  38127. VertexData.CreateIcoSphere = function (options) {
  38128. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38129. var radius = options.radius || 1;
  38130. var flat = (options.flat === undefined) ? true : options.flat;
  38131. var subdivisions = options.subdivisions || 4;
  38132. var radiusX = options.radiusX || radius;
  38133. var radiusY = options.radiusY || radius;
  38134. var radiusZ = options.radiusZ || radius;
  38135. var t = (1 + Math.sqrt(5)) / 2;
  38136. // 12 vertex x,y,z
  38137. var ico_vertices = [
  38138. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38139. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38140. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38141. ];
  38142. // index of 3 vertex makes a face of icopshere
  38143. var ico_indices = [
  38144. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38145. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38146. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38147. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38148. ];
  38149. // vertex for uv have aliased position, not for UV
  38150. var vertices_unalias_id = [
  38151. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38152. // vertex alias
  38153. 0,
  38154. 2,
  38155. 3,
  38156. 3,
  38157. 3,
  38158. 4,
  38159. 7,
  38160. 8,
  38161. 9,
  38162. 9,
  38163. 10,
  38164. 11 // 23: B + 12
  38165. ];
  38166. // uv as integer step (not pixels !)
  38167. var ico_vertexuv = [
  38168. 5, 1, 3, 1, 6, 4, 0, 0,
  38169. 5, 3, 4, 2, 2, 2, 4, 0,
  38170. 2, 0, 1, 1, 6, 0, 6, 2,
  38171. // vertex alias (for same vertex on different faces)
  38172. 0, 4,
  38173. 3, 3,
  38174. 4, 4,
  38175. 3, 1,
  38176. 4, 2,
  38177. 4, 4,
  38178. 0, 2,
  38179. 1, 1,
  38180. 2, 2,
  38181. 3, 3,
  38182. 1, 3,
  38183. 2, 4 // 23: B + 12
  38184. ];
  38185. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38186. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38187. // First island of uv mapping
  38188. // v = 4h 3+ 2
  38189. // v = 3h 9+ 4
  38190. // v = 2h 9+ 5 B
  38191. // v = 1h 9 1 0
  38192. // v = 0h 3 8 7 A
  38193. // u = 0 1 2 3 4 5 6 *a
  38194. // Second island of uv mapping
  38195. // v = 4h 0+ B+ 4+
  38196. // v = 3h A+ 2+
  38197. // v = 2h 7+ 6 3+
  38198. // v = 1h 8+ 3+
  38199. // v = 0h
  38200. // u = 0 1 2 3 4 5 6 *a
  38201. // Face layout on texture UV mapping
  38202. // ============
  38203. // \ 4 /\ 16 / ======
  38204. // \ / \ / /\ 11 /
  38205. // \/ 7 \/ / \ /
  38206. // ======= / 10 \/
  38207. // /\ 17 /\ =======
  38208. // / \ / \ \ 15 /\
  38209. // / 8 \/ 12 \ \ / \
  38210. // ============ \/ 6 \
  38211. // \ 18 /\ ============
  38212. // \ / \ \ 5 /\ 0 /
  38213. // \/ 13 \ \ / \ /
  38214. // ======= \/ 1 \/
  38215. // =============
  38216. // /\ 19 /\ 2 /\
  38217. // / \ / \ / \
  38218. // / 14 \/ 9 \/ 3 \
  38219. // ===================
  38220. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38221. var ustep = 138 / 1024;
  38222. var vstep = 239 / 1024;
  38223. var uoffset = 60 / 1024;
  38224. var voffset = 26 / 1024;
  38225. // Second island should have margin, not to touch the first island
  38226. // avoid any borderline artefact in pixel rounding
  38227. var island_u_offset = -40 / 1024;
  38228. var island_v_offset = +20 / 1024;
  38229. // face is either island 0 or 1 :
  38230. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38231. var island = [
  38232. 0, 0, 0, 0, 1,
  38233. 0, 0, 1, 1, 0,
  38234. 0, 0, 1, 1, 0,
  38235. 0, 1, 1, 1, 0 // 15 - 19
  38236. ];
  38237. var indices = new Array();
  38238. var positions = new Array();
  38239. var normals = new Array();
  38240. var uvs = new Array();
  38241. var current_indice = 0;
  38242. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38243. var face_vertex_pos = new Array(3);
  38244. var face_vertex_uv = new Array(3);
  38245. var v012;
  38246. for (v012 = 0; v012 < 3; v012++) {
  38247. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38248. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38249. }
  38250. // create all with normals
  38251. for (var face = 0; face < 20; face++) {
  38252. // 3 vertex per face
  38253. for (v012 = 0; v012 < 3; v012++) {
  38254. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38255. var v_id = ico_indices[3 * face + v012];
  38256. // vertex have 3D position (x,y,z)
  38257. 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]);
  38258. // Normalize to get normal, then scale to radius
  38259. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38260. // uv Coordinates from vertex ID
  38261. 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);
  38262. }
  38263. // Subdivide the face (interpolate pos, norm, uv)
  38264. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38265. // - norm is linear interpolation of vertex corner normal
  38266. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38267. // - uv is linear interpolation
  38268. //
  38269. // Topology is as below for sub-divide by 2
  38270. // vertex shown as v0,v1,v2
  38271. // interp index is i1 to progress in range [v0,v1[
  38272. // interp index is i2 to progress in range [v0,v2[
  38273. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38274. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38275. //
  38276. //
  38277. // i2 v2
  38278. // ^ ^
  38279. // / / \
  38280. // / / \
  38281. // / / \
  38282. // / / (0,1) \
  38283. // / #---------\
  38284. // / / \ (0,0)'/ \
  38285. // / / \ / \
  38286. // / / \ / \
  38287. // / / (0,0) \ / (1,0) \
  38288. // / #---------#---------\
  38289. // v0 v1
  38290. //
  38291. // --------------------> i1
  38292. //
  38293. // interp of (i1,i2):
  38294. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38295. // along i1 : lerp(x0,x1, i1/(S-i2))
  38296. //
  38297. // centroid of triangle is needed to get help normal computation
  38298. // (c1,c2) are used for centroid location
  38299. var interp_vertex = function (i1, i2, c1, c2) {
  38300. // vertex is interpolated from
  38301. // - face_vertex_pos[0..2]
  38302. // - face_vertex_uv[0..2]
  38303. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38304. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38305. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38306. pos_interp.normalize();
  38307. var vertex_normal;
  38308. if (flat) {
  38309. // in flat mode, recalculate normal as face centroid normal
  38310. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38311. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38312. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38313. }
  38314. else {
  38315. // in smooth mode, recalculate normal from each single vertex position
  38316. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38317. }
  38318. // Vertex normal need correction due to X,Y,Z radius scaling
  38319. vertex_normal.x /= radiusX;
  38320. vertex_normal.y /= radiusY;
  38321. vertex_normal.z /= radiusZ;
  38322. vertex_normal.normalize();
  38323. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38324. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38325. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38326. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38327. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38328. uvs.push(uv_interp.x, uv_interp.y);
  38329. // push each vertex has member of a face
  38330. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38331. indices.push(current_indice);
  38332. current_indice++;
  38333. };
  38334. for (var i2 = 0; i2 < subdivisions; i2++) {
  38335. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38336. // face : (i1,i2) for /\ :
  38337. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38338. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38339. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38340. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38341. if (i1 + i2 + 1 < subdivisions) {
  38342. // face : (i1,i2)' for \/ :
  38343. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38344. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38345. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38346. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38347. }
  38348. }
  38349. }
  38350. }
  38351. // Sides
  38352. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38353. // Result
  38354. var vertexData = new VertexData();
  38355. vertexData.indices = indices;
  38356. vertexData.positions = positions;
  38357. vertexData.normals = normals;
  38358. vertexData.uvs = uvs;
  38359. return vertexData;
  38360. };
  38361. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38362. /**
  38363. * Creates the VertexData for a Polyhedron
  38364. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38365. * * type provided types are:
  38366. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38367. * * 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)
  38368. * * size the size of the IcoSphere, optional default 1
  38369. * * sizeX allows stretching in the x direction, optional, default size
  38370. * * sizeY allows stretching in the y direction, optional, default size
  38371. * * sizeZ allows stretching in the z direction, optional, default size
  38372. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38373. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38374. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38375. * * flat when true creates a flat shaded mesh, optional, default true
  38376. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38377. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38378. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38379. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38380. * @returns the VertexData of the Polyhedron
  38381. */
  38382. VertexData.CreatePolyhedron = function (options) {
  38383. // provided polyhedron types :
  38384. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38385. // 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)
  38386. var polyhedra = [];
  38387. 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]] };
  38388. 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]] };
  38389. polyhedra[2] = {
  38390. 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]],
  38391. 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]]
  38392. };
  38393. polyhedra[3] = {
  38394. 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]],
  38395. 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]]
  38396. };
  38397. polyhedra[4] = {
  38398. 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]],
  38399. 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]]
  38400. };
  38401. 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]] };
  38402. 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]] };
  38403. 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]] };
  38404. 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]] };
  38405. 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]] };
  38406. 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]] };
  38407. 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]] };
  38408. 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]] };
  38409. 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]] };
  38410. polyhedra[14] = {
  38411. 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]],
  38412. 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]]
  38413. };
  38414. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38415. var size = options.size;
  38416. var sizeX = options.sizeX || size || 1;
  38417. var sizeY = options.sizeY || size || 1;
  38418. var sizeZ = options.sizeZ || size || 1;
  38419. var data = options.custom || polyhedra[type];
  38420. var nbfaces = data.face.length;
  38421. var faceUV = options.faceUV || new Array(nbfaces);
  38422. var faceColors = options.faceColors;
  38423. var flat = (options.flat === undefined) ? true : options.flat;
  38424. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38425. var positions = new Array();
  38426. var indices = new Array();
  38427. var normals = new Array();
  38428. var uvs = new Array();
  38429. var colors = new Array();
  38430. var index = 0;
  38431. var faceIdx = 0; // face cursor in the array "indexes"
  38432. var indexes = new Array();
  38433. var i = 0;
  38434. var f = 0;
  38435. var u, v, ang, x, y, tmp;
  38436. // default face colors and UV if undefined
  38437. if (flat) {
  38438. for (f = 0; f < nbfaces; f++) {
  38439. if (faceColors && faceColors[f] === undefined) {
  38440. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38441. }
  38442. if (faceUV && faceUV[f] === undefined) {
  38443. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38444. }
  38445. }
  38446. }
  38447. if (!flat) {
  38448. for (i = 0; i < data.vertex.length; i++) {
  38449. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38450. uvs.push(0, 0);
  38451. }
  38452. for (f = 0; f < nbfaces; f++) {
  38453. for (i = 0; i < data.face[f].length - 2; i++) {
  38454. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38455. }
  38456. }
  38457. }
  38458. else {
  38459. for (f = 0; f < nbfaces; f++) {
  38460. var fl = data.face[f].length; // number of vertices of the current face
  38461. ang = 2 * Math.PI / fl;
  38462. x = 0.5 * Math.tan(ang / 2);
  38463. y = 0.5;
  38464. // positions, uvs, colors
  38465. for (i = 0; i < fl; i++) {
  38466. // positions
  38467. 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);
  38468. indexes.push(index);
  38469. index++;
  38470. // uvs
  38471. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38472. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38473. uvs.push(u, v);
  38474. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38475. y = x * Math.sin(ang) + y * Math.cos(ang);
  38476. x = tmp;
  38477. // colors
  38478. if (faceColors) {
  38479. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38480. }
  38481. }
  38482. // indices from indexes
  38483. for (i = 0; i < fl - 2; i++) {
  38484. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38485. }
  38486. faceIdx += fl;
  38487. }
  38488. }
  38489. VertexData.ComputeNormals(positions, indices, normals);
  38490. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38491. var vertexData = new VertexData();
  38492. vertexData.positions = positions;
  38493. vertexData.indices = indices;
  38494. vertexData.normals = normals;
  38495. vertexData.uvs = uvs;
  38496. if (faceColors && flat) {
  38497. vertexData.colors = colors;
  38498. }
  38499. return vertexData;
  38500. };
  38501. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38502. /**
  38503. * Creates the VertexData for a TorusKnot
  38504. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38505. * * radius the radius of the torus knot, optional, default 2
  38506. * * tube the thickness of the tube, optional, default 0.5
  38507. * * radialSegments the number of sides on each tube segments, optional, default 32
  38508. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38509. * * p the number of windings around the z axis, optional, default 2
  38510. * * q the number of windings around the x axis, optional, default 3
  38511. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38512. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38513. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38514. * @returns the VertexData of the Torus Knot
  38515. */
  38516. VertexData.CreateTorusKnot = function (options) {
  38517. var indices = new Array();
  38518. var positions = new Array();
  38519. var normals = new Array();
  38520. var uvs = new Array();
  38521. var radius = options.radius || 2;
  38522. var tube = options.tube || 0.5;
  38523. var radialSegments = options.radialSegments || 32;
  38524. var tubularSegments = options.tubularSegments || 32;
  38525. var p = options.p || 2;
  38526. var q = options.q || 3;
  38527. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38528. // Helper
  38529. var getPos = function (angle) {
  38530. var cu = Math.cos(angle);
  38531. var su = Math.sin(angle);
  38532. var quOverP = q / p * angle;
  38533. var cs = Math.cos(quOverP);
  38534. var tx = radius * (2 + cs) * 0.5 * cu;
  38535. var ty = radius * (2 + cs) * su * 0.5;
  38536. var tz = radius * Math.sin(quOverP) * 0.5;
  38537. return new BABYLON.Vector3(tx, ty, tz);
  38538. };
  38539. // Vertices
  38540. var i;
  38541. var j;
  38542. for (i = 0; i <= radialSegments; i++) {
  38543. var modI = i % radialSegments;
  38544. var u = modI / radialSegments * 2 * p * Math.PI;
  38545. var p1 = getPos(u);
  38546. var p2 = getPos(u + 0.01);
  38547. var tang = p2.subtract(p1);
  38548. var n = p2.add(p1);
  38549. var bitan = BABYLON.Vector3.Cross(tang, n);
  38550. n = BABYLON.Vector3.Cross(bitan, tang);
  38551. bitan.normalize();
  38552. n.normalize();
  38553. for (j = 0; j < tubularSegments; j++) {
  38554. var modJ = j % tubularSegments;
  38555. var v = modJ / tubularSegments * 2 * Math.PI;
  38556. var cx = -tube * Math.cos(v);
  38557. var cy = tube * Math.sin(v);
  38558. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38559. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38560. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38561. uvs.push(i / radialSegments);
  38562. uvs.push(j / tubularSegments);
  38563. }
  38564. }
  38565. for (i = 0; i < radialSegments; i++) {
  38566. for (j = 0; j < tubularSegments; j++) {
  38567. var jNext = (j + 1) % tubularSegments;
  38568. var a = i * tubularSegments + j;
  38569. var b = (i + 1) * tubularSegments + j;
  38570. var c = (i + 1) * tubularSegments + jNext;
  38571. var d = i * tubularSegments + jNext;
  38572. indices.push(d);
  38573. indices.push(b);
  38574. indices.push(a);
  38575. indices.push(d);
  38576. indices.push(c);
  38577. indices.push(b);
  38578. }
  38579. }
  38580. // Normals
  38581. VertexData.ComputeNormals(positions, indices, normals);
  38582. // Sides
  38583. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38584. // Result
  38585. var vertexData = new VertexData();
  38586. vertexData.indices = indices;
  38587. vertexData.positions = positions;
  38588. vertexData.normals = normals;
  38589. vertexData.uvs = uvs;
  38590. return vertexData;
  38591. };
  38592. // Tools
  38593. /**
  38594. * Compute normals for given positions and indices
  38595. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38596. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38597. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38598. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38599. * * facetNormals : optional array of facet normals (vector3)
  38600. * * facetPositions : optional array of facet positions (vector3)
  38601. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38602. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38603. * * bInfo : optional bounding info, required for facetPartitioning computation
  38604. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38605. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38606. * * useRightHandedSystem: optional boolean to for right handed system computation
  38607. * * depthSort : optional boolean to enable the facet depth sort computation
  38608. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38609. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38610. */
  38611. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38612. // temporary scalar variables
  38613. var index = 0; // facet index
  38614. var p1p2x = 0.0; // p1p2 vector x coordinate
  38615. var p1p2y = 0.0; // p1p2 vector y coordinate
  38616. var p1p2z = 0.0; // p1p2 vector z coordinate
  38617. var p3p2x = 0.0; // p3p2 vector x coordinate
  38618. var p3p2y = 0.0; // p3p2 vector y coordinate
  38619. var p3p2z = 0.0; // p3p2 vector z coordinate
  38620. var faceNormalx = 0.0; // facet normal x coordinate
  38621. var faceNormaly = 0.0; // facet normal y coordinate
  38622. var faceNormalz = 0.0; // facet normal z coordinate
  38623. var length = 0.0; // facet normal length before normalization
  38624. var v1x = 0; // vector1 x index in the positions array
  38625. var v1y = 0; // vector1 y index in the positions array
  38626. var v1z = 0; // vector1 z index in the positions array
  38627. var v2x = 0; // vector2 x index in the positions array
  38628. var v2y = 0; // vector2 y index in the positions array
  38629. var v2z = 0; // vector2 z index in the positions array
  38630. var v3x = 0; // vector3 x index in the positions array
  38631. var v3y = 0; // vector3 y index in the positions array
  38632. var v3z = 0; // vector3 z index in the positions array
  38633. var computeFacetNormals = false;
  38634. var computeFacetPositions = false;
  38635. var computeFacetPartitioning = false;
  38636. var computeDepthSort = false;
  38637. var faceNormalSign = 1;
  38638. var ratio = 0;
  38639. var distanceTo = null;
  38640. if (options) {
  38641. computeFacetNormals = (options.facetNormals) ? true : false;
  38642. computeFacetPositions = (options.facetPositions) ? true : false;
  38643. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38644. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38645. ratio = options.ratio || 0;
  38646. computeDepthSort = (options.depthSort) ? true : false;
  38647. distanceTo = (options.distanceTo);
  38648. if (computeDepthSort) {
  38649. if (distanceTo === undefined) {
  38650. distanceTo = BABYLON.Vector3.Zero();
  38651. }
  38652. var depthSortedFacets = options.depthSortedFacets;
  38653. }
  38654. }
  38655. // facetPartitioning reinit if needed
  38656. var xSubRatio = 0;
  38657. var ySubRatio = 0;
  38658. var zSubRatio = 0;
  38659. var subSq = 0;
  38660. if (computeFacetPartitioning && options && options.bbSize) {
  38661. var ox = 0; // X partitioning index for facet position
  38662. var oy = 0; // Y partinioning index for facet position
  38663. var oz = 0; // Z partinioning index for facet position
  38664. var b1x = 0; // X partitioning index for facet v1 vertex
  38665. var b1y = 0; // Y partitioning index for facet v1 vertex
  38666. var b1z = 0; // z partitioning index for facet v1 vertex
  38667. var b2x = 0; // X partitioning index for facet v2 vertex
  38668. var b2y = 0; // Y partitioning index for facet v2 vertex
  38669. var b2z = 0; // Z partitioning index for facet v2 vertex
  38670. var b3x = 0; // X partitioning index for facet v3 vertex
  38671. var b3y = 0; // Y partitioning index for facet v3 vertex
  38672. var b3z = 0; // Z partitioning index for facet v3 vertex
  38673. var block_idx_o = 0; // facet barycenter block index
  38674. var block_idx_v1 = 0; // v1 vertex block index
  38675. var block_idx_v2 = 0; // v2 vertex block index
  38676. var block_idx_v3 = 0; // v3 vertex block index
  38677. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38678. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38679. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38680. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38681. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38682. subSq = options.subDiv.max * options.subDiv.max;
  38683. options.facetPartitioning.length = 0;
  38684. }
  38685. // reset the normals
  38686. for (index = 0; index < positions.length; index++) {
  38687. normals[index] = 0.0;
  38688. }
  38689. // Loop : 1 indice triplet = 1 facet
  38690. var nbFaces = (indices.length / 3) | 0;
  38691. for (index = 0; index < nbFaces; index++) {
  38692. // get the indexes of the coordinates of each vertex of the facet
  38693. v1x = indices[index * 3] * 3;
  38694. v1y = v1x + 1;
  38695. v1z = v1x + 2;
  38696. v2x = indices[index * 3 + 1] * 3;
  38697. v2y = v2x + 1;
  38698. v2z = v2x + 2;
  38699. v3x = indices[index * 3 + 2] * 3;
  38700. v3y = v3x + 1;
  38701. v3z = v3x + 2;
  38702. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38703. p1p2y = positions[v1y] - positions[v2y];
  38704. p1p2z = positions[v1z] - positions[v2z];
  38705. p3p2x = positions[v3x] - positions[v2x];
  38706. p3p2y = positions[v3y] - positions[v2y];
  38707. p3p2z = positions[v3z] - positions[v2z];
  38708. // compute the face normal with the cross product
  38709. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38710. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38711. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38712. // normalize this normal and store it in the array facetData
  38713. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38714. length = (length === 0) ? 1.0 : length;
  38715. faceNormalx /= length;
  38716. faceNormaly /= length;
  38717. faceNormalz /= length;
  38718. if (computeFacetNormals && options) {
  38719. options.facetNormals[index].x = faceNormalx;
  38720. options.facetNormals[index].y = faceNormaly;
  38721. options.facetNormals[index].z = faceNormalz;
  38722. }
  38723. if (computeFacetPositions && options) {
  38724. // compute and the facet barycenter coordinates in the array facetPositions
  38725. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38726. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38727. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38728. }
  38729. if (computeFacetPartitioning && options) {
  38730. // store the facet indexes in arrays in the main facetPartitioning array :
  38731. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38732. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38733. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38734. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38735. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38736. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38737. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38738. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38739. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38740. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38741. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38742. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38743. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38744. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38745. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38746. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38747. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38748. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38749. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38750. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38751. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38752. // push each facet index in each block containing the vertex
  38753. options.facetPartitioning[block_idx_v1].push(index);
  38754. if (block_idx_v2 != block_idx_v1) {
  38755. options.facetPartitioning[block_idx_v2].push(index);
  38756. }
  38757. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38758. options.facetPartitioning[block_idx_v3].push(index);
  38759. }
  38760. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38761. options.facetPartitioning[block_idx_o].push(index);
  38762. }
  38763. }
  38764. if (computeDepthSort && options && options.facetPositions) {
  38765. var dsf = depthSortedFacets[index];
  38766. dsf.ind = index * 3;
  38767. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38768. }
  38769. // compute the normals anyway
  38770. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38771. normals[v1y] += faceNormaly;
  38772. normals[v1z] += faceNormalz;
  38773. normals[v2x] += faceNormalx;
  38774. normals[v2y] += faceNormaly;
  38775. normals[v2z] += faceNormalz;
  38776. normals[v3x] += faceNormalx;
  38777. normals[v3y] += faceNormaly;
  38778. normals[v3z] += faceNormalz;
  38779. }
  38780. // last normalization of each normal
  38781. for (index = 0; index < normals.length / 3; index++) {
  38782. faceNormalx = normals[index * 3];
  38783. faceNormaly = normals[index * 3 + 1];
  38784. faceNormalz = normals[index * 3 + 2];
  38785. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38786. length = (length === 0) ? 1.0 : length;
  38787. faceNormalx /= length;
  38788. faceNormaly /= length;
  38789. faceNormalz /= length;
  38790. normals[index * 3] = faceNormalx;
  38791. normals[index * 3 + 1] = faceNormaly;
  38792. normals[index * 3 + 2] = faceNormalz;
  38793. }
  38794. };
  38795. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38796. var li = indices.length;
  38797. var ln = normals.length;
  38798. var i;
  38799. var n;
  38800. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38801. switch (sideOrientation) {
  38802. case BABYLON.Mesh.FRONTSIDE:
  38803. // nothing changed
  38804. break;
  38805. case BABYLON.Mesh.BACKSIDE:
  38806. var tmp;
  38807. // indices
  38808. for (i = 0; i < li; i += 3) {
  38809. tmp = indices[i];
  38810. indices[i] = indices[i + 2];
  38811. indices[i + 2] = tmp;
  38812. }
  38813. // normals
  38814. for (n = 0; n < ln; n++) {
  38815. normals[n] = -normals[n];
  38816. }
  38817. break;
  38818. case BABYLON.Mesh.DOUBLESIDE:
  38819. // positions
  38820. var lp = positions.length;
  38821. var l = lp / 3;
  38822. for (var p = 0; p < lp; p++) {
  38823. positions[lp + p] = positions[p];
  38824. }
  38825. // indices
  38826. for (i = 0; i < li; i += 3) {
  38827. indices[i + li] = indices[i + 2] + l;
  38828. indices[i + 1 + li] = indices[i + 1] + l;
  38829. indices[i + 2 + li] = indices[i] + l;
  38830. }
  38831. // normals
  38832. for (n = 0; n < ln; n++) {
  38833. normals[ln + n] = -normals[n];
  38834. }
  38835. // uvs
  38836. var lu = uvs.length;
  38837. var u = 0;
  38838. for (u = 0; u < lu; u++) {
  38839. uvs[u + lu] = uvs[u];
  38840. }
  38841. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38842. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38843. u = 0;
  38844. for (i = 0; i < lu / 2; i++) {
  38845. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38846. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38847. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38848. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38849. u += 2;
  38850. }
  38851. break;
  38852. }
  38853. };
  38854. /**
  38855. * Applies VertexData created from the imported parameters to the geometry
  38856. * @param parsedVertexData the parsed data from an imported file
  38857. * @param geometry the geometry to apply the VertexData to
  38858. */
  38859. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38860. var vertexData = new VertexData();
  38861. // positions
  38862. var positions = parsedVertexData.positions;
  38863. if (positions) {
  38864. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38865. }
  38866. // normals
  38867. var normals = parsedVertexData.normals;
  38868. if (normals) {
  38869. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38870. }
  38871. // tangents
  38872. var tangents = parsedVertexData.tangents;
  38873. if (tangents) {
  38874. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38875. }
  38876. // uvs
  38877. var uvs = parsedVertexData.uvs;
  38878. if (uvs) {
  38879. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38880. }
  38881. // uv2s
  38882. var uv2s = parsedVertexData.uv2s;
  38883. if (uv2s) {
  38884. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38885. }
  38886. // uv3s
  38887. var uv3s = parsedVertexData.uv3s;
  38888. if (uv3s) {
  38889. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38890. }
  38891. // uv4s
  38892. var uv4s = parsedVertexData.uv4s;
  38893. if (uv4s) {
  38894. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38895. }
  38896. // uv5s
  38897. var uv5s = parsedVertexData.uv5s;
  38898. if (uv5s) {
  38899. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38900. }
  38901. // uv6s
  38902. var uv6s = parsedVertexData.uv6s;
  38903. if (uv6s) {
  38904. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38905. }
  38906. // colors
  38907. var colors = parsedVertexData.colors;
  38908. if (colors) {
  38909. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38910. }
  38911. // matricesIndices
  38912. var matricesIndices = parsedVertexData.matricesIndices;
  38913. if (matricesIndices) {
  38914. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38915. }
  38916. // matricesWeights
  38917. var matricesWeights = parsedVertexData.matricesWeights;
  38918. if (matricesWeights) {
  38919. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38920. }
  38921. // indices
  38922. var indices = parsedVertexData.indices;
  38923. if (indices) {
  38924. vertexData.indices = indices;
  38925. }
  38926. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38927. };
  38928. return VertexData;
  38929. }());
  38930. BABYLON.VertexData = VertexData;
  38931. })(BABYLON || (BABYLON = {}));
  38932. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38933. var BABYLON;
  38934. (function (BABYLON) {
  38935. /**
  38936. * Class used to store geometry data (vertex buffers + index buffer)
  38937. */
  38938. var Geometry = /** @class */ (function () {
  38939. /**
  38940. * Creates a new geometry
  38941. * @param id defines the unique ID
  38942. * @param scene defines the hosting scene
  38943. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38944. * @param updatable defines if geometry must be updatable (false by default)
  38945. * @param mesh defines the mesh that will be associated with the geometry
  38946. */
  38947. function Geometry(id, scene, vertexData, updatable, mesh) {
  38948. if (updatable === void 0) { updatable = false; }
  38949. if (mesh === void 0) { mesh = null; }
  38950. /**
  38951. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38952. */
  38953. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38954. this._totalVertices = 0;
  38955. this._isDisposed = false;
  38956. this._indexBufferIsUpdatable = false;
  38957. this.id = id;
  38958. this._engine = scene.getEngine();
  38959. this._meshes = [];
  38960. this._scene = scene;
  38961. //Init vertex buffer cache
  38962. this._vertexBuffers = {};
  38963. this._indices = [];
  38964. this._updatable = updatable;
  38965. // vertexData
  38966. if (vertexData) {
  38967. this.setAllVerticesData(vertexData, updatable);
  38968. }
  38969. else {
  38970. this._totalVertices = 0;
  38971. this._indices = [];
  38972. }
  38973. if (this._engine.getCaps().vertexArrayObject) {
  38974. this._vertexArrayObjects = {};
  38975. }
  38976. // applyToMesh
  38977. if (mesh) {
  38978. if (mesh.getClassName() === "LinesMesh") {
  38979. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38980. this._updateExtend();
  38981. }
  38982. this.applyToMesh(mesh);
  38983. mesh.computeWorldMatrix(true);
  38984. }
  38985. }
  38986. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38987. /**
  38988. * 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
  38989. */
  38990. get: function () {
  38991. return this._boundingBias;
  38992. },
  38993. /**
  38994. * 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
  38995. */
  38996. set: function (value) {
  38997. if (this._boundingBias && this._boundingBias.equals(value)) {
  38998. return;
  38999. }
  39000. this._boundingBias = value.clone();
  39001. this._updateBoundingInfo(true, null);
  39002. },
  39003. enumerable: true,
  39004. configurable: true
  39005. });
  39006. /**
  39007. * Static function used to attach a new empty geometry to a mesh
  39008. * @param mesh defines the mesh to attach the geometry to
  39009. * @returns the new {BABYLON.Geometry}
  39010. */
  39011. Geometry.CreateGeometryForMesh = function (mesh) {
  39012. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39013. geometry.applyToMesh(mesh);
  39014. return geometry;
  39015. };
  39016. Object.defineProperty(Geometry.prototype, "extend", {
  39017. /**
  39018. * Gets the current extend of the geometry
  39019. */
  39020. get: function () {
  39021. return this._extend;
  39022. },
  39023. enumerable: true,
  39024. configurable: true
  39025. });
  39026. /**
  39027. * Gets the hosting scene
  39028. * @returns the hosting {BABYLON.Scene}
  39029. */
  39030. Geometry.prototype.getScene = function () {
  39031. return this._scene;
  39032. };
  39033. /**
  39034. * Gets the hosting engine
  39035. * @returns the hosting {BABYLON.Engine}
  39036. */
  39037. Geometry.prototype.getEngine = function () {
  39038. return this._engine;
  39039. };
  39040. /**
  39041. * Defines if the geometry is ready to use
  39042. * @returns true if the geometry is ready to be used
  39043. */
  39044. Geometry.prototype.isReady = function () {
  39045. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39046. };
  39047. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39048. /**
  39049. * Gets a value indicating that the geometry should not be serialized
  39050. */
  39051. get: function () {
  39052. for (var index = 0; index < this._meshes.length; index++) {
  39053. if (!this._meshes[index].doNotSerialize) {
  39054. return false;
  39055. }
  39056. }
  39057. return true;
  39058. },
  39059. enumerable: true,
  39060. configurable: true
  39061. });
  39062. /** @hidden */
  39063. Geometry.prototype._rebuild = function () {
  39064. if (this._vertexArrayObjects) {
  39065. this._vertexArrayObjects = {};
  39066. }
  39067. // Index buffer
  39068. if (this._meshes.length !== 0 && this._indices) {
  39069. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39070. }
  39071. // Vertex buffers
  39072. for (var key in this._vertexBuffers) {
  39073. var vertexBuffer = this._vertexBuffers[key];
  39074. vertexBuffer._rebuild();
  39075. }
  39076. };
  39077. /**
  39078. * Affects all gemetry data in one call
  39079. * @param vertexData defines the geometry data
  39080. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39081. */
  39082. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39083. vertexData.applyToGeometry(this, updatable);
  39084. this.notifyUpdate();
  39085. };
  39086. /**
  39087. * Set specific vertex data
  39088. * @param kind defines the data kind (Position, normal, etc...)
  39089. * @param data defines the vertex data to use
  39090. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39091. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39092. */
  39093. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39094. if (updatable === void 0) { updatable = false; }
  39095. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39096. this.setVerticesBuffer(buffer);
  39097. };
  39098. /**
  39099. * Removes a specific vertex data
  39100. * @param kind defines the data kind (Position, normal, etc...)
  39101. */
  39102. Geometry.prototype.removeVerticesData = function (kind) {
  39103. if (this._vertexBuffers[kind]) {
  39104. this._vertexBuffers[kind].dispose();
  39105. delete this._vertexBuffers[kind];
  39106. }
  39107. };
  39108. /**
  39109. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39110. * @param buffer defines the vertex buffer to use
  39111. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39112. */
  39113. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39114. if (totalVertices === void 0) { totalVertices = null; }
  39115. var kind = buffer.getKind();
  39116. if (this._vertexBuffers[kind]) {
  39117. this._vertexBuffers[kind].dispose();
  39118. }
  39119. this._vertexBuffers[kind] = buffer;
  39120. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39121. var data = buffer.getData();
  39122. if (totalVertices != null) {
  39123. this._totalVertices = totalVertices;
  39124. }
  39125. else {
  39126. if (data != null) {
  39127. this._totalVertices = data.length / (buffer.byteStride / 4);
  39128. }
  39129. }
  39130. this._updateExtend(data);
  39131. this._resetPointsArrayCache();
  39132. var meshes = this._meshes;
  39133. var numOfMeshes = meshes.length;
  39134. for (var index = 0; index < numOfMeshes; index++) {
  39135. var mesh = meshes[index];
  39136. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39137. mesh._createGlobalSubMesh(false);
  39138. mesh.computeWorldMatrix(true);
  39139. }
  39140. }
  39141. this.notifyUpdate(kind);
  39142. if (this._vertexArrayObjects) {
  39143. this._disposeVertexArrayObjects();
  39144. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39145. }
  39146. };
  39147. /**
  39148. * Update a specific vertex buffer
  39149. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39150. * It will do nothing if the buffer is not updatable
  39151. * @param kind defines the data kind (Position, normal, etc...)
  39152. * @param data defines the data to use
  39153. * @param offset defines the offset in the target buffer where to store the data
  39154. * @param useBytes set to true if the offset is in bytes
  39155. */
  39156. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39157. if (useBytes === void 0) { useBytes = false; }
  39158. var vertexBuffer = this.getVertexBuffer(kind);
  39159. if (!vertexBuffer) {
  39160. return;
  39161. }
  39162. vertexBuffer.updateDirectly(data, offset, useBytes);
  39163. this.notifyUpdate(kind);
  39164. };
  39165. /**
  39166. * Update a specific vertex buffer
  39167. * This function will create a new buffer if the current one is not updatable
  39168. * @param kind defines the data kind (Position, normal, etc...)
  39169. * @param data defines the data to use
  39170. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39171. */
  39172. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39173. if (updateExtends === void 0) { updateExtends = false; }
  39174. var vertexBuffer = this.getVertexBuffer(kind);
  39175. if (!vertexBuffer) {
  39176. return;
  39177. }
  39178. vertexBuffer.update(data);
  39179. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39180. this._updateBoundingInfo(updateExtends, data);
  39181. }
  39182. this.notifyUpdate(kind);
  39183. };
  39184. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39185. if (updateExtends) {
  39186. this._updateExtend(data);
  39187. }
  39188. var meshes = this._meshes;
  39189. var numOfMeshes = meshes.length;
  39190. this._resetPointsArrayCache();
  39191. for (var index = 0; index < numOfMeshes; index++) {
  39192. var mesh = meshes[index];
  39193. if (updateExtends) {
  39194. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39195. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39196. var subMesh = mesh.subMeshes[subIndex];
  39197. subMesh.refreshBoundingInfo();
  39198. }
  39199. }
  39200. }
  39201. };
  39202. /** @hidden */
  39203. Geometry.prototype._bind = function (effect, indexToBind) {
  39204. if (!effect) {
  39205. return;
  39206. }
  39207. if (indexToBind === undefined) {
  39208. indexToBind = this._indexBuffer;
  39209. }
  39210. var vbs = this.getVertexBuffers();
  39211. if (!vbs) {
  39212. return;
  39213. }
  39214. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39215. this._engine.bindBuffers(vbs, indexToBind, effect);
  39216. return;
  39217. }
  39218. // Using VAO
  39219. if (!this._vertexArrayObjects[effect.key]) {
  39220. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39221. }
  39222. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39223. };
  39224. /**
  39225. * Gets total number of vertices
  39226. * @returns the total number of vertices
  39227. */
  39228. Geometry.prototype.getTotalVertices = function () {
  39229. if (!this.isReady()) {
  39230. return 0;
  39231. }
  39232. return this._totalVertices;
  39233. };
  39234. /**
  39235. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39236. * @param kind defines the data kind (Position, normal, etc...)
  39237. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39238. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39239. * @returns a float array containing vertex data
  39240. */
  39241. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39242. var vertexBuffer = this.getVertexBuffer(kind);
  39243. if (!vertexBuffer) {
  39244. return null;
  39245. }
  39246. var data = vertexBuffer.getData();
  39247. if (!data) {
  39248. return null;
  39249. }
  39250. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39251. var count = this._totalVertices * vertexBuffer.getSize();
  39252. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39253. var copy_1 = new Array(count);
  39254. vertexBuffer.forEach(count, function (value, index) {
  39255. copy_1[index] = value;
  39256. });
  39257. return copy_1;
  39258. }
  39259. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39260. if (data instanceof Array) {
  39261. var offset = vertexBuffer.byteOffset / 4;
  39262. return BABYLON.Tools.Slice(data, offset, offset + count);
  39263. }
  39264. else if (data instanceof ArrayBuffer) {
  39265. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39266. }
  39267. else {
  39268. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39269. }
  39270. }
  39271. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39272. return BABYLON.Tools.Slice(data);
  39273. }
  39274. return data;
  39275. };
  39276. /**
  39277. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39278. * @param kind defines the data kind (Position, normal, etc...)
  39279. * @returns true if the vertex buffer with the specified kind is updatable
  39280. */
  39281. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39282. var vb = this._vertexBuffers[kind];
  39283. if (!vb) {
  39284. return false;
  39285. }
  39286. return vb.isUpdatable();
  39287. };
  39288. /**
  39289. * Gets a specific vertex buffer
  39290. * @param kind defines the data kind (Position, normal, etc...)
  39291. * @returns a {BABYLON.VertexBuffer}
  39292. */
  39293. Geometry.prototype.getVertexBuffer = function (kind) {
  39294. if (!this.isReady()) {
  39295. return null;
  39296. }
  39297. return this._vertexBuffers[kind];
  39298. };
  39299. /**
  39300. * Returns all vertex buffers
  39301. * @return an object holding all vertex buffers indexed by kind
  39302. */
  39303. Geometry.prototype.getVertexBuffers = function () {
  39304. if (!this.isReady()) {
  39305. return null;
  39306. }
  39307. return this._vertexBuffers;
  39308. };
  39309. /**
  39310. * Gets a boolean indicating if specific vertex buffer is present
  39311. * @param kind defines the data kind (Position, normal, etc...)
  39312. * @returns true if data is present
  39313. */
  39314. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39315. if (!this._vertexBuffers) {
  39316. if (this._delayInfo) {
  39317. return this._delayInfo.indexOf(kind) !== -1;
  39318. }
  39319. return false;
  39320. }
  39321. return this._vertexBuffers[kind] !== undefined;
  39322. };
  39323. /**
  39324. * Gets a list of all attached data kinds (Position, normal, etc...)
  39325. * @returns a list of string containing all kinds
  39326. */
  39327. Geometry.prototype.getVerticesDataKinds = function () {
  39328. var result = [];
  39329. var kind;
  39330. if (!this._vertexBuffers && this._delayInfo) {
  39331. for (kind in this._delayInfo) {
  39332. result.push(kind);
  39333. }
  39334. }
  39335. else {
  39336. for (kind in this._vertexBuffers) {
  39337. result.push(kind);
  39338. }
  39339. }
  39340. return result;
  39341. };
  39342. /**
  39343. * Update index buffer
  39344. * @param indices defines the indices to store in the index buffer
  39345. * @param offset defines the offset in the target buffer where to store the data
  39346. */
  39347. Geometry.prototype.updateIndices = function (indices, offset) {
  39348. if (!this._indexBuffer) {
  39349. return;
  39350. }
  39351. if (!this._indexBufferIsUpdatable) {
  39352. this.setIndices(indices, null, true);
  39353. }
  39354. else {
  39355. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39356. }
  39357. };
  39358. /**
  39359. * Creates a new index buffer
  39360. * @param indices defines the indices to store in the index buffer
  39361. * @param totalVertices defines the total number of vertices (could be null)
  39362. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39363. */
  39364. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39365. if (totalVertices === void 0) { totalVertices = null; }
  39366. if (updatable === void 0) { updatable = false; }
  39367. if (this._indexBuffer) {
  39368. this._engine._releaseBuffer(this._indexBuffer);
  39369. }
  39370. this._disposeVertexArrayObjects();
  39371. this._indices = indices;
  39372. this._indexBufferIsUpdatable = updatable;
  39373. if (this._meshes.length !== 0 && this._indices) {
  39374. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39375. }
  39376. if (totalVertices != undefined) { // including null and undefined
  39377. this._totalVertices = totalVertices;
  39378. }
  39379. var meshes = this._meshes;
  39380. var numOfMeshes = meshes.length;
  39381. for (var index = 0; index < numOfMeshes; index++) {
  39382. meshes[index]._createGlobalSubMesh(true);
  39383. }
  39384. this.notifyUpdate();
  39385. };
  39386. /**
  39387. * Return the total number of indices
  39388. * @returns the total number of indices
  39389. */
  39390. Geometry.prototype.getTotalIndices = function () {
  39391. if (!this.isReady()) {
  39392. return 0;
  39393. }
  39394. return this._indices.length;
  39395. };
  39396. /**
  39397. * Gets the index buffer array
  39398. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39399. * @returns the index buffer array
  39400. */
  39401. Geometry.prototype.getIndices = function (copyWhenShared) {
  39402. if (!this.isReady()) {
  39403. return null;
  39404. }
  39405. var orig = this._indices;
  39406. if (!copyWhenShared || this._meshes.length === 1) {
  39407. return orig;
  39408. }
  39409. else {
  39410. var len = orig.length;
  39411. var copy = [];
  39412. for (var i = 0; i < len; i++) {
  39413. copy.push(orig[i]);
  39414. }
  39415. return copy;
  39416. }
  39417. };
  39418. /**
  39419. * Gets the index buffer
  39420. * @return the index buffer
  39421. */
  39422. Geometry.prototype.getIndexBuffer = function () {
  39423. if (!this.isReady()) {
  39424. return null;
  39425. }
  39426. return this._indexBuffer;
  39427. };
  39428. /** @hidden */
  39429. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39430. if (effect === void 0) { effect = null; }
  39431. if (!effect || !this._vertexArrayObjects) {
  39432. return;
  39433. }
  39434. if (this._vertexArrayObjects[effect.key]) {
  39435. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39436. delete this._vertexArrayObjects[effect.key];
  39437. }
  39438. };
  39439. /**
  39440. * Release the associated resources for a specific mesh
  39441. * @param mesh defines the source mesh
  39442. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39443. */
  39444. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39445. var meshes = this._meshes;
  39446. var index = meshes.indexOf(mesh);
  39447. if (index === -1) {
  39448. return;
  39449. }
  39450. meshes.splice(index, 1);
  39451. mesh._geometry = null;
  39452. if (meshes.length === 0 && shouldDispose) {
  39453. this.dispose();
  39454. }
  39455. };
  39456. /**
  39457. * Apply current geometry to a given mesh
  39458. * @param mesh defines the mesh to apply geometry to
  39459. */
  39460. Geometry.prototype.applyToMesh = function (mesh) {
  39461. if (mesh._geometry === this) {
  39462. return;
  39463. }
  39464. var previousGeometry = mesh._geometry;
  39465. if (previousGeometry) {
  39466. previousGeometry.releaseForMesh(mesh);
  39467. }
  39468. var meshes = this._meshes;
  39469. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39470. mesh._geometry = this;
  39471. this._scene.pushGeometry(this);
  39472. meshes.push(mesh);
  39473. if (this.isReady()) {
  39474. this._applyToMesh(mesh);
  39475. }
  39476. else {
  39477. mesh._boundingInfo = this._boundingInfo;
  39478. }
  39479. };
  39480. Geometry.prototype._updateExtend = function (data) {
  39481. if (data === void 0) { data = null; }
  39482. if (!data) {
  39483. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39484. }
  39485. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39486. };
  39487. Geometry.prototype._applyToMesh = function (mesh) {
  39488. var numOfMeshes = this._meshes.length;
  39489. // vertexBuffers
  39490. for (var kind in this._vertexBuffers) {
  39491. if (numOfMeshes === 1) {
  39492. this._vertexBuffers[kind].create();
  39493. }
  39494. var buffer = this._vertexBuffers[kind].getBuffer();
  39495. if (buffer)
  39496. buffer.references = numOfMeshes;
  39497. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39498. if (!this._extend) {
  39499. this._updateExtend();
  39500. }
  39501. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39502. mesh._createGlobalSubMesh(false);
  39503. //bounding info was just created again, world matrix should be applied again.
  39504. mesh._updateBoundingInfo();
  39505. }
  39506. }
  39507. // indexBuffer
  39508. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39509. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39510. }
  39511. if (this._indexBuffer) {
  39512. this._indexBuffer.references = numOfMeshes;
  39513. }
  39514. };
  39515. Geometry.prototype.notifyUpdate = function (kind) {
  39516. if (this.onGeometryUpdated) {
  39517. this.onGeometryUpdated(this, kind);
  39518. }
  39519. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39520. var mesh = _a[_i];
  39521. mesh._markSubMeshesAsAttributesDirty();
  39522. }
  39523. };
  39524. /**
  39525. * Load the geometry if it was flagged as delay loaded
  39526. * @param scene defines the hosting scene
  39527. * @param onLoaded defines a callback called when the geometry is loaded
  39528. */
  39529. Geometry.prototype.load = function (scene, onLoaded) {
  39530. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39531. return;
  39532. }
  39533. if (this.isReady()) {
  39534. if (onLoaded) {
  39535. onLoaded();
  39536. }
  39537. return;
  39538. }
  39539. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39540. this._queueLoad(scene, onLoaded);
  39541. };
  39542. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39543. var _this = this;
  39544. if (!this.delayLoadingFile) {
  39545. return;
  39546. }
  39547. scene._addPendingData(this);
  39548. scene._loadFile(this.delayLoadingFile, function (data) {
  39549. if (!_this._delayLoadingFunction) {
  39550. return;
  39551. }
  39552. _this._delayLoadingFunction(JSON.parse(data), _this);
  39553. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39554. _this._delayInfo = [];
  39555. scene._removePendingData(_this);
  39556. var meshes = _this._meshes;
  39557. var numOfMeshes = meshes.length;
  39558. for (var index = 0; index < numOfMeshes; index++) {
  39559. _this._applyToMesh(meshes[index]);
  39560. }
  39561. if (onLoaded) {
  39562. onLoaded();
  39563. }
  39564. }, undefined, true);
  39565. };
  39566. /**
  39567. * Invert the geometry to move from a right handed system to a left handed one.
  39568. */
  39569. Geometry.prototype.toLeftHanded = function () {
  39570. // Flip faces
  39571. var tIndices = this.getIndices(false);
  39572. if (tIndices != null && tIndices.length > 0) {
  39573. for (var i = 0; i < tIndices.length; i += 3) {
  39574. var tTemp = tIndices[i + 0];
  39575. tIndices[i + 0] = tIndices[i + 2];
  39576. tIndices[i + 2] = tTemp;
  39577. }
  39578. this.setIndices(tIndices);
  39579. }
  39580. // Negate position.z
  39581. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39582. if (tPositions != null && tPositions.length > 0) {
  39583. for (var i = 0; i < tPositions.length; i += 3) {
  39584. tPositions[i + 2] = -tPositions[i + 2];
  39585. }
  39586. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39587. }
  39588. // Negate normal.z
  39589. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39590. if (tNormals != null && tNormals.length > 0) {
  39591. for (var i = 0; i < tNormals.length; i += 3) {
  39592. tNormals[i + 2] = -tNormals[i + 2];
  39593. }
  39594. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39595. }
  39596. };
  39597. // Cache
  39598. /** @hidden */
  39599. Geometry.prototype._resetPointsArrayCache = function () {
  39600. this._positions = null;
  39601. };
  39602. /** @hidden */
  39603. Geometry.prototype._generatePointsArray = function () {
  39604. if (this._positions)
  39605. return true;
  39606. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39607. if (!data || data.length === 0) {
  39608. return false;
  39609. }
  39610. this._positions = [];
  39611. for (var index = 0; index < data.length; index += 3) {
  39612. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39613. }
  39614. return true;
  39615. };
  39616. /**
  39617. * Gets a value indicating if the geometry is disposed
  39618. * @returns true if the geometry was disposed
  39619. */
  39620. Geometry.prototype.isDisposed = function () {
  39621. return this._isDisposed;
  39622. };
  39623. Geometry.prototype._disposeVertexArrayObjects = function () {
  39624. if (this._vertexArrayObjects) {
  39625. for (var kind in this._vertexArrayObjects) {
  39626. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39627. }
  39628. this._vertexArrayObjects = {};
  39629. }
  39630. };
  39631. /**
  39632. * Free all associated resources
  39633. */
  39634. Geometry.prototype.dispose = function () {
  39635. var meshes = this._meshes;
  39636. var numOfMeshes = meshes.length;
  39637. var index;
  39638. for (index = 0; index < numOfMeshes; index++) {
  39639. this.releaseForMesh(meshes[index]);
  39640. }
  39641. this._meshes = [];
  39642. this._disposeVertexArrayObjects();
  39643. for (var kind in this._vertexBuffers) {
  39644. this._vertexBuffers[kind].dispose();
  39645. }
  39646. this._vertexBuffers = {};
  39647. this._totalVertices = 0;
  39648. if (this._indexBuffer) {
  39649. this._engine._releaseBuffer(this._indexBuffer);
  39650. }
  39651. this._indexBuffer = null;
  39652. this._indices = [];
  39653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39654. this.delayLoadingFile = null;
  39655. this._delayLoadingFunction = null;
  39656. this._delayInfo = [];
  39657. this._boundingInfo = null;
  39658. this._scene.removeGeometry(this);
  39659. this._isDisposed = true;
  39660. };
  39661. /**
  39662. * Clone the current geometry into a new geometry
  39663. * @param id defines the unique ID of the new geometry
  39664. * @returns a new geometry object
  39665. */
  39666. Geometry.prototype.copy = function (id) {
  39667. var vertexData = new BABYLON.VertexData();
  39668. vertexData.indices = [];
  39669. var indices = this.getIndices();
  39670. if (indices) {
  39671. for (var index = 0; index < indices.length; index++) {
  39672. vertexData.indices.push(indices[index]);
  39673. }
  39674. }
  39675. var updatable = false;
  39676. var stopChecking = false;
  39677. var kind;
  39678. for (kind in this._vertexBuffers) {
  39679. // using slice() to make a copy of the array and not just reference it
  39680. var data = this.getVerticesData(kind);
  39681. if (data instanceof Float32Array) {
  39682. vertexData.set(new Float32Array(data), kind);
  39683. }
  39684. else {
  39685. vertexData.set(data.slice(0), kind);
  39686. }
  39687. if (!stopChecking) {
  39688. var vb = this.getVertexBuffer(kind);
  39689. if (vb) {
  39690. updatable = vb.isUpdatable();
  39691. stopChecking = !updatable;
  39692. }
  39693. }
  39694. }
  39695. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39696. geometry.delayLoadState = this.delayLoadState;
  39697. geometry.delayLoadingFile = this.delayLoadingFile;
  39698. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39699. for (kind in this._delayInfo) {
  39700. geometry._delayInfo = geometry._delayInfo || [];
  39701. geometry._delayInfo.push(kind);
  39702. }
  39703. // Bounding info
  39704. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39705. return geometry;
  39706. };
  39707. /**
  39708. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39709. * @return a JSON representation of the current geometry data (without the vertices data)
  39710. */
  39711. Geometry.prototype.serialize = function () {
  39712. var serializationObject = {};
  39713. serializationObject.id = this.id;
  39714. serializationObject.updatable = this._updatable;
  39715. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39716. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39717. }
  39718. return serializationObject;
  39719. };
  39720. Geometry.prototype.toNumberArray = function (origin) {
  39721. if (Array.isArray(origin)) {
  39722. return origin;
  39723. }
  39724. else {
  39725. return Array.prototype.slice.call(origin);
  39726. }
  39727. };
  39728. /**
  39729. * Serialize all vertices data into a JSON oject
  39730. * @returns a JSON representation of the current geometry data
  39731. */
  39732. Geometry.prototype.serializeVerticeData = function () {
  39733. var serializationObject = this.serialize();
  39734. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39735. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39736. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39737. serializationObject.positions._updatable = true;
  39738. }
  39739. }
  39740. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39741. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39742. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39743. serializationObject.normals._updatable = true;
  39744. }
  39745. }
  39746. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39747. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39748. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39749. serializationObject.tangets._updatable = true;
  39750. }
  39751. }
  39752. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39753. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39754. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39755. serializationObject.uvs._updatable = true;
  39756. }
  39757. }
  39758. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39759. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39760. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39761. serializationObject.uv2s._updatable = true;
  39762. }
  39763. }
  39764. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39765. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39766. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39767. serializationObject.uv3s._updatable = true;
  39768. }
  39769. }
  39770. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39771. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39772. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39773. serializationObject.uv4s._updatable = true;
  39774. }
  39775. }
  39776. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39777. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39778. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39779. serializationObject.uv5s._updatable = true;
  39780. }
  39781. }
  39782. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39783. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39784. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39785. serializationObject.uv6s._updatable = true;
  39786. }
  39787. }
  39788. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39789. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39790. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39791. serializationObject.colors._updatable = true;
  39792. }
  39793. }
  39794. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39795. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39796. serializationObject.matricesIndices._isExpanded = true;
  39797. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39798. serializationObject.matricesIndices._updatable = true;
  39799. }
  39800. }
  39801. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39802. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39803. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39804. serializationObject.matricesWeights._updatable = true;
  39805. }
  39806. }
  39807. serializationObject.indices = this.toNumberArray(this.getIndices());
  39808. return serializationObject;
  39809. };
  39810. // Statics
  39811. /**
  39812. * Extracts a clone of a mesh geometry
  39813. * @param mesh defines the source mesh
  39814. * @param id defines the unique ID of the new geometry object
  39815. * @returns the new geometry object
  39816. */
  39817. Geometry.ExtractFromMesh = function (mesh, id) {
  39818. var geometry = mesh._geometry;
  39819. if (!geometry) {
  39820. return null;
  39821. }
  39822. return geometry.copy(id);
  39823. };
  39824. /**
  39825. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39826. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39827. * Be aware Math.random() could cause collisions, but:
  39828. * "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"
  39829. * @returns a string containing a new GUID
  39830. */
  39831. Geometry.RandomId = function () {
  39832. return BABYLON.Tools.RandomId();
  39833. };
  39834. /** @hidden */
  39835. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39836. var scene = mesh.getScene();
  39837. // Geometry
  39838. var geometryId = parsedGeometry.geometryId;
  39839. if (geometryId) {
  39840. var geometry = scene.getGeometryByID(geometryId);
  39841. if (geometry) {
  39842. geometry.applyToMesh(mesh);
  39843. }
  39844. }
  39845. else if (parsedGeometry instanceof ArrayBuffer) {
  39846. var binaryInfo = mesh._binaryInfo;
  39847. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39848. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39849. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39850. }
  39851. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39852. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39853. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39854. }
  39855. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39856. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39857. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39858. }
  39859. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39860. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39861. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39862. }
  39863. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39864. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39865. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39866. }
  39867. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39868. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39869. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39870. }
  39871. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39872. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39873. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39874. }
  39875. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39876. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39877. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39878. }
  39879. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39880. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39881. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39882. }
  39883. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39884. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39885. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39886. }
  39887. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39888. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39889. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39890. }
  39891. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39892. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39893. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39894. }
  39895. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39896. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39897. mesh.setIndices(indicesData, null);
  39898. }
  39899. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39900. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39901. mesh.subMeshes = [];
  39902. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39903. var materialIndex = subMeshesData[(i * 5) + 0];
  39904. var verticesStart = subMeshesData[(i * 5) + 1];
  39905. var verticesCount = subMeshesData[(i * 5) + 2];
  39906. var indexStart = subMeshesData[(i * 5) + 3];
  39907. var indexCount = subMeshesData[(i * 5) + 4];
  39908. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39909. }
  39910. }
  39911. }
  39912. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39913. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39914. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39915. if (parsedGeometry.tangents) {
  39916. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39917. }
  39918. if (parsedGeometry.uvs) {
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39920. }
  39921. if (parsedGeometry.uvs2) {
  39922. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39923. }
  39924. if (parsedGeometry.uvs3) {
  39925. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39926. }
  39927. if (parsedGeometry.uvs4) {
  39928. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39929. }
  39930. if (parsedGeometry.uvs5) {
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39932. }
  39933. if (parsedGeometry.uvs6) {
  39934. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39935. }
  39936. if (parsedGeometry.colors) {
  39937. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39938. }
  39939. if (parsedGeometry.matricesIndices) {
  39940. if (!parsedGeometry.matricesIndices._isExpanded) {
  39941. var floatIndices = [];
  39942. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39943. var matricesIndex = parsedGeometry.matricesIndices[i];
  39944. floatIndices.push(matricesIndex & 0x000000FF);
  39945. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39946. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39947. floatIndices.push(matricesIndex >> 24);
  39948. }
  39949. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39950. }
  39951. else {
  39952. delete parsedGeometry.matricesIndices._isExpanded;
  39953. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39954. }
  39955. }
  39956. if (parsedGeometry.matricesIndicesExtra) {
  39957. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39958. var floatIndices = [];
  39959. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39960. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39961. floatIndices.push(matricesIndex & 0x000000FF);
  39962. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39963. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39964. floatIndices.push(matricesIndex >> 24);
  39965. }
  39966. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39967. }
  39968. else {
  39969. delete parsedGeometry.matricesIndices._isExpanded;
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39971. }
  39972. }
  39973. if (parsedGeometry.matricesWeights) {
  39974. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39976. }
  39977. if (parsedGeometry.matricesWeightsExtra) {
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39979. }
  39980. mesh.setIndices(parsedGeometry.indices, null);
  39981. }
  39982. // SubMeshes
  39983. if (parsedGeometry.subMeshes) {
  39984. mesh.subMeshes = [];
  39985. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39986. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39987. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39988. }
  39989. }
  39990. // Flat shading
  39991. if (mesh._shouldGenerateFlatShading) {
  39992. mesh.convertToFlatShadedMesh();
  39993. delete mesh._shouldGenerateFlatShading;
  39994. }
  39995. // Update
  39996. mesh.computeWorldMatrix(true);
  39997. // Octree
  39998. var sceneOctree = scene.selectionOctree;
  39999. if (sceneOctree !== undefined && sceneOctree !== null) {
  40000. sceneOctree.addMesh(mesh);
  40001. }
  40002. };
  40003. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40004. var epsilon = 1e-3;
  40005. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40006. return;
  40007. }
  40008. var noInfluenceBoneIndex = 0.0;
  40009. if (parsedGeometry.skeletonId > -1) {
  40010. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40011. if (!skeleton) {
  40012. return;
  40013. }
  40014. noInfluenceBoneIndex = skeleton.bones.length;
  40015. }
  40016. else {
  40017. return;
  40018. }
  40019. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40020. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40021. var matricesWeights = parsedGeometry.matricesWeights;
  40022. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40023. var influencers = parsedGeometry.numBoneInfluencer;
  40024. var size = matricesWeights.length;
  40025. for (var i = 0; i < size; i += 4) {
  40026. var weight = 0.0;
  40027. var firstZeroWeight = -1;
  40028. for (var j = 0; j < 4; j++) {
  40029. var w = matricesWeights[i + j];
  40030. weight += w;
  40031. if (w < epsilon && firstZeroWeight < 0) {
  40032. firstZeroWeight = j;
  40033. }
  40034. }
  40035. if (matricesWeightsExtra) {
  40036. for (var j = 0; j < 4; j++) {
  40037. var w = matricesWeightsExtra[i + j];
  40038. weight += w;
  40039. if (w < epsilon && firstZeroWeight < 0) {
  40040. firstZeroWeight = j + 4;
  40041. }
  40042. }
  40043. }
  40044. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40045. firstZeroWeight = influencers - 1;
  40046. }
  40047. if (weight > epsilon) {
  40048. var mweight = 1.0 / weight;
  40049. for (var j = 0; j < 4; j++) {
  40050. matricesWeights[i + j] *= mweight;
  40051. }
  40052. if (matricesWeightsExtra) {
  40053. for (var j = 0; j < 4; j++) {
  40054. matricesWeightsExtra[i + j] *= mweight;
  40055. }
  40056. }
  40057. }
  40058. else {
  40059. if (firstZeroWeight >= 4) {
  40060. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40061. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40062. }
  40063. else {
  40064. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40065. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40066. }
  40067. }
  40068. }
  40069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40070. if (parsedGeometry.matricesWeightsExtra) {
  40071. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40072. }
  40073. };
  40074. /**
  40075. * Create a new geometry from persisted data (Using .babylon file format)
  40076. * @param parsedVertexData defines the persisted data
  40077. * @param scene defines the hosting scene
  40078. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40079. * @returns the new geometry object
  40080. */
  40081. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40082. if (scene.getGeometryByID(parsedVertexData.id)) {
  40083. return null; // null since geometry could be something else than a box...
  40084. }
  40085. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40086. if (BABYLON.Tags) {
  40087. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40088. }
  40089. if (parsedVertexData.delayLoadingFile) {
  40090. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40091. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40092. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40093. geometry._delayInfo = [];
  40094. if (parsedVertexData.hasUVs) {
  40095. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40096. }
  40097. if (parsedVertexData.hasUVs2) {
  40098. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40099. }
  40100. if (parsedVertexData.hasUVs3) {
  40101. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40102. }
  40103. if (parsedVertexData.hasUVs4) {
  40104. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40105. }
  40106. if (parsedVertexData.hasUVs5) {
  40107. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40108. }
  40109. if (parsedVertexData.hasUVs6) {
  40110. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40111. }
  40112. if (parsedVertexData.hasColors) {
  40113. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40114. }
  40115. if (parsedVertexData.hasMatricesIndices) {
  40116. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40117. }
  40118. if (parsedVertexData.hasMatricesWeights) {
  40119. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40120. }
  40121. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40122. }
  40123. else {
  40124. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40125. }
  40126. scene.pushGeometry(geometry, true);
  40127. return geometry;
  40128. };
  40129. return Geometry;
  40130. }());
  40131. BABYLON.Geometry = Geometry;
  40132. // Primitives
  40133. /// Abstract class
  40134. /**
  40135. * Abstract class used to provide common services for all typed geometries
  40136. * @hidden
  40137. */
  40138. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40139. __extends(_PrimitiveGeometry, _super);
  40140. /**
  40141. * Creates a new typed geometry
  40142. * @param id defines the unique ID of the geometry
  40143. * @param scene defines the hosting scene
  40144. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40145. * @param mesh defines the hosting mesh (can be null)
  40146. */
  40147. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40148. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40149. if (mesh === void 0) { mesh = null; }
  40150. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40151. _this._canBeRegenerated = _canBeRegenerated;
  40152. _this._beingRegenerated = true;
  40153. _this.regenerate();
  40154. _this._beingRegenerated = false;
  40155. return _this;
  40156. }
  40157. /**
  40158. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40159. * @returns true if the geometry can be regenerated
  40160. */
  40161. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40162. return this._canBeRegenerated;
  40163. };
  40164. /**
  40165. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40166. */
  40167. _PrimitiveGeometry.prototype.regenerate = function () {
  40168. if (!this._canBeRegenerated) {
  40169. return;
  40170. }
  40171. this._beingRegenerated = true;
  40172. this.setAllVerticesData(this._regenerateVertexData(), false);
  40173. this._beingRegenerated = false;
  40174. };
  40175. /**
  40176. * Clone the geometry
  40177. * @param id defines the unique ID of the new geometry
  40178. * @returns the new geometry
  40179. */
  40180. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40181. return _super.prototype.copy.call(this, id);
  40182. };
  40183. // overrides
  40184. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40185. if (!this._beingRegenerated) {
  40186. return;
  40187. }
  40188. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40189. };
  40190. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40191. if (!this._beingRegenerated) {
  40192. return;
  40193. }
  40194. _super.prototype.setVerticesData.call(this, kind, data, false);
  40195. };
  40196. // to override
  40197. /** @hidden */
  40198. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40199. throw new Error("Abstract method");
  40200. };
  40201. _PrimitiveGeometry.prototype.copy = function (id) {
  40202. throw new Error("Must be overriden in sub-classes.");
  40203. };
  40204. _PrimitiveGeometry.prototype.serialize = function () {
  40205. var serializationObject = _super.prototype.serialize.call(this);
  40206. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40207. return serializationObject;
  40208. };
  40209. return _PrimitiveGeometry;
  40210. }(Geometry));
  40211. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40212. /**
  40213. * Creates a ribbon geometry
  40214. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40215. */
  40216. var RibbonGeometry = /** @class */ (function (_super) {
  40217. __extends(RibbonGeometry, _super);
  40218. /**
  40219. * Creates a ribbon geometry
  40220. * @param id defines the unique ID of the geometry
  40221. * @param scene defines the hosting scene
  40222. * @param pathArray defines the array of paths to use
  40223. * @param closeArray defines if the last path and the first path must be joined
  40224. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40225. * @param offset defines the offset between points
  40226. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40227. * @param mesh defines the hosting mesh (can be null)
  40228. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40229. */
  40230. function RibbonGeometry(id, scene,
  40231. /**
  40232. * Defines the array of paths to use
  40233. */
  40234. pathArray,
  40235. /**
  40236. * Defines if the last and first points of each path in your pathArray must be joined
  40237. */
  40238. closeArray,
  40239. /**
  40240. * Defines if the last and first points of each path in your pathArray must be joined
  40241. */
  40242. closePath,
  40243. /**
  40244. * Defines the offset between points
  40245. */
  40246. offset, canBeRegenerated, mesh,
  40247. /**
  40248. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40249. */
  40250. side) {
  40251. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40252. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40253. _this.pathArray = pathArray;
  40254. _this.closeArray = closeArray;
  40255. _this.closePath = closePath;
  40256. _this.offset = offset;
  40257. _this.side = side;
  40258. return _this;
  40259. }
  40260. /** @hidden */
  40261. RibbonGeometry.prototype._regenerateVertexData = function () {
  40262. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40263. };
  40264. RibbonGeometry.prototype.copy = function (id) {
  40265. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40266. };
  40267. return RibbonGeometry;
  40268. }(_PrimitiveGeometry));
  40269. BABYLON.RibbonGeometry = RibbonGeometry;
  40270. /**
  40271. * Creates a box geometry
  40272. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40273. */
  40274. var BoxGeometry = /** @class */ (function (_super) {
  40275. __extends(BoxGeometry, _super);
  40276. /**
  40277. * Creates a box geometry
  40278. * @param id defines the unique ID of the geometry
  40279. * @param scene defines the hosting scene
  40280. * @param size defines the zise of the box (width, height and depth are the same)
  40281. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40282. * @param mesh defines the hosting mesh (can be null)
  40283. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40284. */
  40285. function BoxGeometry(id, scene,
  40286. /**
  40287. * Defines the zise of the box (width, height and depth are the same)
  40288. */
  40289. size, canBeRegenerated, mesh,
  40290. /**
  40291. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40292. */
  40293. side) {
  40294. if (mesh === void 0) { mesh = null; }
  40295. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40296. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40297. _this.size = size;
  40298. _this.side = side;
  40299. return _this;
  40300. }
  40301. BoxGeometry.prototype._regenerateVertexData = function () {
  40302. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40303. };
  40304. BoxGeometry.prototype.copy = function (id) {
  40305. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40306. };
  40307. BoxGeometry.prototype.serialize = function () {
  40308. var serializationObject = _super.prototype.serialize.call(this);
  40309. serializationObject.size = this.size;
  40310. return serializationObject;
  40311. };
  40312. BoxGeometry.Parse = function (parsedBox, scene) {
  40313. if (scene.getGeometryByID(parsedBox.id)) {
  40314. return null; // null since geometry could be something else than a box...
  40315. }
  40316. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40317. if (BABYLON.Tags) {
  40318. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40319. }
  40320. scene.pushGeometry(box, true);
  40321. return box;
  40322. };
  40323. return BoxGeometry;
  40324. }(_PrimitiveGeometry));
  40325. BABYLON.BoxGeometry = BoxGeometry;
  40326. /**
  40327. * Creates a sphere geometry
  40328. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40329. */
  40330. var SphereGeometry = /** @class */ (function (_super) {
  40331. __extends(SphereGeometry, _super);
  40332. /**
  40333. * Create a new sphere geometry
  40334. * @param id defines the unique ID of the geometry
  40335. * @param scene defines the hosting scene
  40336. * @param segments defines the number of segments to use to create the sphere
  40337. * @param diameter defines the diameter of the sphere
  40338. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40339. * @param mesh defines the hosting mesh (can be null)
  40340. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40341. */
  40342. function SphereGeometry(id, scene,
  40343. /**
  40344. * Defines the number of segments to use to create the sphere
  40345. */
  40346. segments,
  40347. /**
  40348. * Defines the diameter of the sphere
  40349. */
  40350. diameter, canBeRegenerated, mesh,
  40351. /**
  40352. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40353. */
  40354. side) {
  40355. if (mesh === void 0) { mesh = null; }
  40356. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40357. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40358. _this.segments = segments;
  40359. _this.diameter = diameter;
  40360. _this.side = side;
  40361. return _this;
  40362. }
  40363. SphereGeometry.prototype._regenerateVertexData = function () {
  40364. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40365. };
  40366. SphereGeometry.prototype.copy = function (id) {
  40367. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40368. };
  40369. SphereGeometry.prototype.serialize = function () {
  40370. var serializationObject = _super.prototype.serialize.call(this);
  40371. serializationObject.segments = this.segments;
  40372. serializationObject.diameter = this.diameter;
  40373. return serializationObject;
  40374. };
  40375. SphereGeometry.Parse = function (parsedSphere, scene) {
  40376. if (scene.getGeometryByID(parsedSphere.id)) {
  40377. return null; // null since geometry could be something else than a sphere...
  40378. }
  40379. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40380. if (BABYLON.Tags) {
  40381. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40382. }
  40383. scene.pushGeometry(sphere, true);
  40384. return sphere;
  40385. };
  40386. return SphereGeometry;
  40387. }(_PrimitiveGeometry));
  40388. BABYLON.SphereGeometry = SphereGeometry;
  40389. /**
  40390. * Creates a disc geometry
  40391. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40392. */
  40393. var DiscGeometry = /** @class */ (function (_super) {
  40394. __extends(DiscGeometry, _super);
  40395. /**
  40396. * Creates a new disc geometry
  40397. * @param id defines the unique ID of the geometry
  40398. * @param scene defines the hosting scene
  40399. * @param radius defines the radius of the disc
  40400. * @param tessellation defines the tesselation factor to apply to the disc
  40401. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40402. * @param mesh defines the hosting mesh (can be null)
  40403. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40404. */
  40405. function DiscGeometry(id, scene,
  40406. /**
  40407. * Defines the radius of the disc
  40408. */
  40409. radius,
  40410. /**
  40411. * Defines the tesselation factor to apply to the disc
  40412. */
  40413. tessellation, canBeRegenerated, mesh,
  40414. /**
  40415. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40416. */
  40417. side) {
  40418. if (mesh === void 0) { mesh = null; }
  40419. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40420. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40421. _this.radius = radius;
  40422. _this.tessellation = tessellation;
  40423. _this.side = side;
  40424. return _this;
  40425. }
  40426. DiscGeometry.prototype._regenerateVertexData = function () {
  40427. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40428. };
  40429. DiscGeometry.prototype.copy = function (id) {
  40430. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40431. };
  40432. return DiscGeometry;
  40433. }(_PrimitiveGeometry));
  40434. BABYLON.DiscGeometry = DiscGeometry;
  40435. /**
  40436. * Creates a new cylinder geometry
  40437. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40438. */
  40439. var CylinderGeometry = /** @class */ (function (_super) {
  40440. __extends(CylinderGeometry, _super);
  40441. /**
  40442. * Creates a new cylinder geometry
  40443. * @param id defines the unique ID of the geometry
  40444. * @param scene defines the hosting scene
  40445. * @param height defines the height of the cylinder
  40446. * @param diameterTop defines the diameter of the cylinder's top cap
  40447. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40448. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40449. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40450. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40451. * @param mesh defines the hosting mesh (can be null)
  40452. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40453. */
  40454. function CylinderGeometry(id, scene,
  40455. /**
  40456. * Defines the height of the cylinder
  40457. */
  40458. height,
  40459. /**
  40460. * Defines the diameter of the cylinder's top cap
  40461. */
  40462. diameterTop,
  40463. /**
  40464. * Defines the diameter of the cylinder's bottom cap
  40465. */
  40466. diameterBottom,
  40467. /**
  40468. * Defines the tessellation factor to apply to the cylinder
  40469. */
  40470. tessellation,
  40471. /**
  40472. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40473. */
  40474. subdivisions, canBeRegenerated, mesh,
  40475. /**
  40476. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40477. */
  40478. side) {
  40479. if (subdivisions === void 0) { subdivisions = 1; }
  40480. if (mesh === void 0) { mesh = null; }
  40481. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40482. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40483. _this.height = height;
  40484. _this.diameterTop = diameterTop;
  40485. _this.diameterBottom = diameterBottom;
  40486. _this.tessellation = tessellation;
  40487. _this.subdivisions = subdivisions;
  40488. _this.side = side;
  40489. return _this;
  40490. }
  40491. CylinderGeometry.prototype._regenerateVertexData = function () {
  40492. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40493. };
  40494. CylinderGeometry.prototype.copy = function (id) {
  40495. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40496. };
  40497. CylinderGeometry.prototype.serialize = function () {
  40498. var serializationObject = _super.prototype.serialize.call(this);
  40499. serializationObject.height = this.height;
  40500. serializationObject.diameterTop = this.diameterTop;
  40501. serializationObject.diameterBottom = this.diameterBottom;
  40502. serializationObject.tessellation = this.tessellation;
  40503. return serializationObject;
  40504. };
  40505. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40506. if (scene.getGeometryByID(parsedCylinder.id)) {
  40507. return null; // null since geometry could be something else than a cylinder...
  40508. }
  40509. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40510. if (BABYLON.Tags) {
  40511. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40512. }
  40513. scene.pushGeometry(cylinder, true);
  40514. return cylinder;
  40515. };
  40516. return CylinderGeometry;
  40517. }(_PrimitiveGeometry));
  40518. BABYLON.CylinderGeometry = CylinderGeometry;
  40519. /**
  40520. * Creates a new torus geometry
  40521. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40522. */
  40523. var TorusGeometry = /** @class */ (function (_super) {
  40524. __extends(TorusGeometry, _super);
  40525. /**
  40526. * Creates a new torus geometry
  40527. * @param id defines the unique ID of the geometry
  40528. * @param scene defines the hosting scene
  40529. * @param diameter defines the diameter of the torus
  40530. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40531. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40532. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40533. * @param mesh defines the hosting mesh (can be null)
  40534. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40535. */
  40536. function TorusGeometry(id, scene,
  40537. /**
  40538. * Defines the diameter of the torus
  40539. */
  40540. diameter,
  40541. /**
  40542. * Defines the thickness of the torus (ie. internal diameter)
  40543. */
  40544. thickness,
  40545. /**
  40546. * Defines the tesselation factor to apply to the torus
  40547. */
  40548. tessellation, canBeRegenerated, mesh,
  40549. /**
  40550. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40551. */
  40552. side) {
  40553. if (mesh === void 0) { mesh = null; }
  40554. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40555. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40556. _this.diameter = diameter;
  40557. _this.thickness = thickness;
  40558. _this.tessellation = tessellation;
  40559. _this.side = side;
  40560. return _this;
  40561. }
  40562. TorusGeometry.prototype._regenerateVertexData = function () {
  40563. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40564. };
  40565. TorusGeometry.prototype.copy = function (id) {
  40566. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40567. };
  40568. TorusGeometry.prototype.serialize = function () {
  40569. var serializationObject = _super.prototype.serialize.call(this);
  40570. serializationObject.diameter = this.diameter;
  40571. serializationObject.thickness = this.thickness;
  40572. serializationObject.tessellation = this.tessellation;
  40573. return serializationObject;
  40574. };
  40575. TorusGeometry.Parse = function (parsedTorus, scene) {
  40576. if (scene.getGeometryByID(parsedTorus.id)) {
  40577. return null; // null since geometry could be something else than a torus...
  40578. }
  40579. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40580. if (BABYLON.Tags) {
  40581. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40582. }
  40583. scene.pushGeometry(torus, true);
  40584. return torus;
  40585. };
  40586. return TorusGeometry;
  40587. }(_PrimitiveGeometry));
  40588. BABYLON.TorusGeometry = TorusGeometry;
  40589. /**
  40590. * Creates a new ground geometry
  40591. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40592. */
  40593. var GroundGeometry = /** @class */ (function (_super) {
  40594. __extends(GroundGeometry, _super);
  40595. /**
  40596. * Creates a new ground geometry
  40597. * @param id defines the unique ID of the geometry
  40598. * @param scene defines the hosting scene
  40599. * @param width defines the width of the ground
  40600. * @param height defines the height of the ground
  40601. * @param subdivisions defines the subdivisions to apply to the ground
  40602. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40603. * @param mesh defines the hosting mesh (can be null)
  40604. */
  40605. function GroundGeometry(id, scene,
  40606. /**
  40607. * Defines the width of the ground
  40608. */
  40609. width,
  40610. /**
  40611. * Defines the height of the ground
  40612. */
  40613. height,
  40614. /**
  40615. * Defines the subdivisions to apply to the ground
  40616. */
  40617. subdivisions, canBeRegenerated, mesh) {
  40618. if (mesh === void 0) { mesh = null; }
  40619. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40620. _this.width = width;
  40621. _this.height = height;
  40622. _this.subdivisions = subdivisions;
  40623. return _this;
  40624. }
  40625. GroundGeometry.prototype._regenerateVertexData = function () {
  40626. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40627. };
  40628. GroundGeometry.prototype.copy = function (id) {
  40629. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40630. };
  40631. GroundGeometry.prototype.serialize = function () {
  40632. var serializationObject = _super.prototype.serialize.call(this);
  40633. serializationObject.width = this.width;
  40634. serializationObject.height = this.height;
  40635. serializationObject.subdivisions = this.subdivisions;
  40636. return serializationObject;
  40637. };
  40638. GroundGeometry.Parse = function (parsedGround, scene) {
  40639. if (scene.getGeometryByID(parsedGround.id)) {
  40640. return null; // null since geometry could be something else than a ground...
  40641. }
  40642. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40643. if (BABYLON.Tags) {
  40644. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40645. }
  40646. scene.pushGeometry(ground, true);
  40647. return ground;
  40648. };
  40649. return GroundGeometry;
  40650. }(_PrimitiveGeometry));
  40651. BABYLON.GroundGeometry = GroundGeometry;
  40652. /**
  40653. * Creates a tiled ground geometry
  40654. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40655. */
  40656. var TiledGroundGeometry = /** @class */ (function (_super) {
  40657. __extends(TiledGroundGeometry, _super);
  40658. /**
  40659. * Creates a tiled ground geometry
  40660. * @param id defines the unique ID of the geometry
  40661. * @param scene defines the hosting scene
  40662. * @param xmin defines the minimum value on X axis
  40663. * @param zmin defines the minimum value on Z axis
  40664. * @param xmax defines the maximum value on X axis
  40665. * @param zmax defines the maximum value on Z axis
  40666. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40667. * @param precision defines the precision to use when computing the tiles
  40668. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40669. * @param mesh defines the hosting mesh (can be null)
  40670. */
  40671. function TiledGroundGeometry(id, scene,
  40672. /**
  40673. * Defines the minimum value on X axis
  40674. */
  40675. xmin,
  40676. /**
  40677. * Defines the minimum value on Z axis
  40678. */
  40679. zmin,
  40680. /**
  40681. * Defines the maximum value on X axis
  40682. */
  40683. xmax,
  40684. /**
  40685. * Defines the maximum value on Z axis
  40686. */
  40687. zmax,
  40688. /**
  40689. * Defines the subdivisions to apply to the ground
  40690. */
  40691. subdivisions,
  40692. /**
  40693. * Defines the precision to use when computing the tiles
  40694. */
  40695. precision, canBeRegenerated, mesh) {
  40696. if (mesh === void 0) { mesh = null; }
  40697. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40698. _this.xmin = xmin;
  40699. _this.zmin = zmin;
  40700. _this.xmax = xmax;
  40701. _this.zmax = zmax;
  40702. _this.subdivisions = subdivisions;
  40703. _this.precision = precision;
  40704. return _this;
  40705. }
  40706. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40707. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40708. };
  40709. TiledGroundGeometry.prototype.copy = function (id) {
  40710. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40711. };
  40712. return TiledGroundGeometry;
  40713. }(_PrimitiveGeometry));
  40714. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40715. /**
  40716. * Creates a plane geometry
  40717. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40718. */
  40719. var PlaneGeometry = /** @class */ (function (_super) {
  40720. __extends(PlaneGeometry, _super);
  40721. /**
  40722. * Creates a plane geometry
  40723. * @param id defines the unique ID of the geometry
  40724. * @param scene defines the hosting scene
  40725. * @param size defines the size of the plane (width === height)
  40726. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40727. * @param mesh defines the hosting mesh (can be null)
  40728. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40729. */
  40730. function PlaneGeometry(id, scene,
  40731. /**
  40732. * Defines the size of the plane (width === height)
  40733. */
  40734. size, canBeRegenerated, mesh,
  40735. /**
  40736. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40737. */
  40738. side) {
  40739. if (mesh === void 0) { mesh = null; }
  40740. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40741. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40742. _this.size = size;
  40743. _this.side = side;
  40744. return _this;
  40745. }
  40746. PlaneGeometry.prototype._regenerateVertexData = function () {
  40747. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40748. };
  40749. PlaneGeometry.prototype.copy = function (id) {
  40750. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40751. };
  40752. PlaneGeometry.prototype.serialize = function () {
  40753. var serializationObject = _super.prototype.serialize.call(this);
  40754. serializationObject.size = this.size;
  40755. return serializationObject;
  40756. };
  40757. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40758. if (scene.getGeometryByID(parsedPlane.id)) {
  40759. return null; // null since geometry could be something else than a ground...
  40760. }
  40761. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40762. if (BABYLON.Tags) {
  40763. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40764. }
  40765. scene.pushGeometry(plane, true);
  40766. return plane;
  40767. };
  40768. return PlaneGeometry;
  40769. }(_PrimitiveGeometry));
  40770. BABYLON.PlaneGeometry = PlaneGeometry;
  40771. /**
  40772. * Creates a torus knot geometry
  40773. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40774. */
  40775. var TorusKnotGeometry = /** @class */ (function (_super) {
  40776. __extends(TorusKnotGeometry, _super);
  40777. /**
  40778. * Creates a torus knot geometry
  40779. * @param id defines the unique ID of the geometry
  40780. * @param scene defines the hosting scene
  40781. * @param radius defines the radius of the torus knot
  40782. * @param tube defines the thickness of the torus knot tube
  40783. * @param radialSegments defines the number of radial segments
  40784. * @param tubularSegments defines the number of tubular segments
  40785. * @param p defines the first number of windings
  40786. * @param q defines the second number of windings
  40787. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40788. * @param mesh defines the hosting mesh (can be null)
  40789. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40790. */
  40791. function TorusKnotGeometry(id, scene,
  40792. /**
  40793. * Defines the radius of the torus knot
  40794. */
  40795. radius,
  40796. /**
  40797. * Defines the thickness of the torus knot tube
  40798. */
  40799. tube,
  40800. /**
  40801. * Defines the number of radial segments
  40802. */
  40803. radialSegments,
  40804. /**
  40805. * Defines the number of tubular segments
  40806. */
  40807. tubularSegments,
  40808. /**
  40809. * Defines the first number of windings
  40810. */
  40811. p,
  40812. /**
  40813. * Defines the second number of windings
  40814. */
  40815. q, canBeRegenerated, mesh,
  40816. /**
  40817. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40818. */
  40819. side) {
  40820. if (mesh === void 0) { mesh = null; }
  40821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40822. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40823. _this.radius = radius;
  40824. _this.tube = tube;
  40825. _this.radialSegments = radialSegments;
  40826. _this.tubularSegments = tubularSegments;
  40827. _this.p = p;
  40828. _this.q = q;
  40829. _this.side = side;
  40830. return _this;
  40831. }
  40832. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40833. 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 });
  40834. };
  40835. TorusKnotGeometry.prototype.copy = function (id) {
  40836. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40837. };
  40838. TorusKnotGeometry.prototype.serialize = function () {
  40839. var serializationObject = _super.prototype.serialize.call(this);
  40840. serializationObject.radius = this.radius;
  40841. serializationObject.tube = this.tube;
  40842. serializationObject.radialSegments = this.radialSegments;
  40843. serializationObject.tubularSegments = this.tubularSegments;
  40844. serializationObject.p = this.p;
  40845. serializationObject.q = this.q;
  40846. return serializationObject;
  40847. };
  40848. ;
  40849. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40850. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40851. return null; // null since geometry could be something else than a ground...
  40852. }
  40853. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40854. if (BABYLON.Tags) {
  40855. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40856. }
  40857. scene.pushGeometry(torusKnot, true);
  40858. return torusKnot;
  40859. };
  40860. return TorusKnotGeometry;
  40861. }(_PrimitiveGeometry));
  40862. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40863. //}
  40864. })(BABYLON || (BABYLON = {}));
  40865. //# sourceMappingURL=babylon.geometry.js.map
  40866. var BABYLON;
  40867. (function (BABYLON) {
  40868. /**
  40869. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40870. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40871. */
  40872. var PostProcessManager = /** @class */ (function () {
  40873. /**
  40874. * Creates a new instance PostProcess
  40875. * @param scene The scene that the post process is associated with.
  40876. */
  40877. function PostProcessManager(scene) {
  40878. this._vertexBuffers = {};
  40879. this._scene = scene;
  40880. }
  40881. PostProcessManager.prototype._prepareBuffers = function () {
  40882. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40883. return;
  40884. }
  40885. // VBO
  40886. var vertices = [];
  40887. vertices.push(1, 1);
  40888. vertices.push(-1, 1);
  40889. vertices.push(-1, -1);
  40890. vertices.push(1, -1);
  40891. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40892. this._buildIndexBuffer();
  40893. };
  40894. PostProcessManager.prototype._buildIndexBuffer = function () {
  40895. // Indices
  40896. var indices = [];
  40897. indices.push(0);
  40898. indices.push(1);
  40899. indices.push(2);
  40900. indices.push(0);
  40901. indices.push(2);
  40902. indices.push(3);
  40903. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40904. };
  40905. /**
  40906. * Rebuilds the vertex buffers of the manager.
  40907. */
  40908. PostProcessManager.prototype._rebuild = function () {
  40909. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40910. if (!vb) {
  40911. return;
  40912. }
  40913. vb._rebuild();
  40914. this._buildIndexBuffer();
  40915. };
  40916. // Methods
  40917. /**
  40918. * Prepares a frame to be run through a post process.
  40919. * @param sourceTexture The input texture to the post procesess. (default: null)
  40920. * @param postProcesses An array of post processes to be run. (default: null)
  40921. * @returns True if the post processes were able to be run.
  40922. */
  40923. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40924. if (sourceTexture === void 0) { sourceTexture = null; }
  40925. if (postProcesses === void 0) { postProcesses = null; }
  40926. var camera = this._scene.activeCamera;
  40927. if (!camera) {
  40928. return false;
  40929. }
  40930. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40931. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40932. return false;
  40933. }
  40934. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40935. return true;
  40936. };
  40937. /**
  40938. * Manually render a set of post processes to a texture.
  40939. * @param postProcesses An array of post processes to be run.
  40940. * @param targetTexture The target texture to render to.
  40941. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40942. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  40943. * @param lodLevel defines which lod of the texture to render to
  40944. */
  40945. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  40946. if (targetTexture === void 0) { targetTexture = null; }
  40947. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40948. if (faceIndex === void 0) { faceIndex = 0; }
  40949. if (lodLevel === void 0) { lodLevel = 0; }
  40950. var engine = this._scene.getEngine();
  40951. for (var index = 0; index < postProcesses.length; index++) {
  40952. if (index < postProcesses.length - 1) {
  40953. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40954. }
  40955. else {
  40956. if (targetTexture) {
  40957. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  40958. }
  40959. else {
  40960. engine.restoreDefaultFramebuffer();
  40961. }
  40962. }
  40963. var pp = postProcesses[index];
  40964. var effect = pp.apply();
  40965. if (effect) {
  40966. pp.onBeforeRenderObservable.notifyObservers(effect);
  40967. // VBOs
  40968. this._prepareBuffers();
  40969. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40970. // Draw order
  40971. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40972. pp.onAfterRenderObservable.notifyObservers(effect);
  40973. }
  40974. }
  40975. // Restore depth buffer
  40976. engine.setDepthBuffer(true);
  40977. engine.setDepthWrite(true);
  40978. };
  40979. /**
  40980. * Finalize the result of the output of the postprocesses.
  40981. * @param doNotPresent If true the result will not be displayed to the screen.
  40982. * @param targetTexture The target texture to render to.
  40983. * @param faceIndex The index of the face to bind the target texture to.
  40984. * @param postProcesses The array of post processes to render.
  40985. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40986. */
  40987. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40988. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40989. var camera = this._scene.activeCamera;
  40990. if (!camera) {
  40991. return;
  40992. }
  40993. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40994. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40995. return;
  40996. }
  40997. var engine = this._scene.getEngine();
  40998. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40999. var pp = postProcesses[index];
  41000. if (index < len - 1) {
  41001. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  41002. }
  41003. else {
  41004. if (targetTexture) {
  41005. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  41006. pp._outputTexture = targetTexture;
  41007. }
  41008. else {
  41009. engine.restoreDefaultFramebuffer();
  41010. pp._outputTexture = null;
  41011. }
  41012. }
  41013. if (doNotPresent) {
  41014. break;
  41015. }
  41016. var effect = pp.apply();
  41017. if (effect) {
  41018. pp.onBeforeRenderObservable.notifyObservers(effect);
  41019. // VBOs
  41020. this._prepareBuffers();
  41021. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41022. // Draw order
  41023. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  41024. pp.onAfterRenderObservable.notifyObservers(effect);
  41025. }
  41026. }
  41027. // Restore states
  41028. engine.setDepthBuffer(true);
  41029. engine.setDepthWrite(true);
  41030. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41031. };
  41032. /**
  41033. * Disposes of the post process manager.
  41034. */
  41035. PostProcessManager.prototype.dispose = function () {
  41036. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  41037. if (buffer) {
  41038. buffer.dispose();
  41039. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  41040. }
  41041. if (this._indexBuffer) {
  41042. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41043. this._indexBuffer = null;
  41044. }
  41045. };
  41046. return PostProcessManager;
  41047. }());
  41048. BABYLON.PostProcessManager = PostProcessManager;
  41049. })(BABYLON || (BABYLON = {}));
  41050. //# sourceMappingURL=babylon.postProcessManager.js.map
  41051. var BABYLON;
  41052. (function (BABYLON) {
  41053. /**
  41054. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41055. */
  41056. var PerformanceMonitor = /** @class */ (function () {
  41057. /**
  41058. * constructor
  41059. * @param frameSampleSize The number of samples required to saturate the sliding window
  41060. */
  41061. function PerformanceMonitor(frameSampleSize) {
  41062. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41063. this._enabled = true;
  41064. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41065. }
  41066. /**
  41067. * Samples current frame
  41068. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41069. */
  41070. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41071. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41072. if (!this._enabled)
  41073. return;
  41074. if (this._lastFrameTimeMs != null) {
  41075. var dt = timeMs - this._lastFrameTimeMs;
  41076. this._rollingFrameTime.add(dt);
  41077. }
  41078. this._lastFrameTimeMs = timeMs;
  41079. };
  41080. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41081. /**
  41082. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41083. * @return Average frame time in milliseconds
  41084. */
  41085. get: function () {
  41086. return this._rollingFrameTime.average;
  41087. },
  41088. enumerable: true,
  41089. configurable: true
  41090. });
  41091. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41092. /**
  41093. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41094. * @return Frame time variance in milliseconds squared
  41095. */
  41096. get: function () {
  41097. return this._rollingFrameTime.variance;
  41098. },
  41099. enumerable: true,
  41100. configurable: true
  41101. });
  41102. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41103. /**
  41104. * Returns the frame time of the most recent frame
  41105. * @return Frame time in milliseconds
  41106. */
  41107. get: function () {
  41108. return this._rollingFrameTime.history(0);
  41109. },
  41110. enumerable: true,
  41111. configurable: true
  41112. });
  41113. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41114. /**
  41115. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41116. * @return Framerate in frames per second
  41117. */
  41118. get: function () {
  41119. return 1000.0 / this._rollingFrameTime.average;
  41120. },
  41121. enumerable: true,
  41122. configurable: true
  41123. });
  41124. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41125. /**
  41126. * Returns the average framerate in frames per second using the most recent frame time
  41127. * @return Framerate in frames per second
  41128. */
  41129. get: function () {
  41130. var history = this._rollingFrameTime.history(0);
  41131. if (history === 0) {
  41132. return 0;
  41133. }
  41134. return 1000.0 / history;
  41135. },
  41136. enumerable: true,
  41137. configurable: true
  41138. });
  41139. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41140. /**
  41141. * Returns true if enough samples have been taken to completely fill the sliding window
  41142. * @return true if saturated
  41143. */
  41144. get: function () {
  41145. return this._rollingFrameTime.isSaturated();
  41146. },
  41147. enumerable: true,
  41148. configurable: true
  41149. });
  41150. /**
  41151. * Enables contributions to the sliding window sample set
  41152. */
  41153. PerformanceMonitor.prototype.enable = function () {
  41154. this._enabled = true;
  41155. };
  41156. /**
  41157. * Disables contributions to the sliding window sample set
  41158. * Samples will not be interpolated over the disabled period
  41159. */
  41160. PerformanceMonitor.prototype.disable = function () {
  41161. this._enabled = false;
  41162. //clear last sample to avoid interpolating over the disabled period when next enabled
  41163. this._lastFrameTimeMs = null;
  41164. };
  41165. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41166. /**
  41167. * Returns true if sampling is enabled
  41168. * @return true if enabled
  41169. */
  41170. get: function () {
  41171. return this._enabled;
  41172. },
  41173. enumerable: true,
  41174. configurable: true
  41175. });
  41176. /**
  41177. * Resets performance monitor
  41178. */
  41179. PerformanceMonitor.prototype.reset = function () {
  41180. //clear last sample to avoid interpolating over the disabled period when next enabled
  41181. this._lastFrameTimeMs = null;
  41182. //wipe record
  41183. this._rollingFrameTime.reset();
  41184. };
  41185. return PerformanceMonitor;
  41186. }());
  41187. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41188. /**
  41189. * RollingAverage
  41190. *
  41191. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41192. */
  41193. var RollingAverage = /** @class */ (function () {
  41194. /**
  41195. * constructor
  41196. * @param length The number of samples required to saturate the sliding window
  41197. */
  41198. function RollingAverage(length) {
  41199. this._samples = new Array(length);
  41200. this.reset();
  41201. }
  41202. /**
  41203. * Adds a sample to the sample set
  41204. * @param v The sample value
  41205. */
  41206. RollingAverage.prototype.add = function (v) {
  41207. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41208. var delta;
  41209. //we need to check if we've already wrapped round
  41210. if (this.isSaturated()) {
  41211. //remove bottom of stack from mean
  41212. var bottomValue = this._samples[this._pos];
  41213. delta = bottomValue - this.average;
  41214. this.average -= delta / (this._sampleCount - 1);
  41215. this._m2 -= delta * (bottomValue - this.average);
  41216. }
  41217. else {
  41218. this._sampleCount++;
  41219. }
  41220. //add new value to mean
  41221. delta = v - this.average;
  41222. this.average += delta / (this._sampleCount);
  41223. this._m2 += delta * (v - this.average);
  41224. //set the new variance
  41225. this.variance = this._m2 / (this._sampleCount - 1);
  41226. this._samples[this._pos] = v;
  41227. this._pos++;
  41228. this._pos %= this._samples.length; //positive wrap around
  41229. };
  41230. /**
  41231. * Returns previously added values or null if outside of history or outside the sliding window domain
  41232. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41233. * @return Value previously recorded with add() or null if outside of range
  41234. */
  41235. RollingAverage.prototype.history = function (i) {
  41236. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41237. return 0;
  41238. }
  41239. var i0 = this._wrapPosition(this._pos - 1.0);
  41240. return this._samples[this._wrapPosition(i0 - i)];
  41241. };
  41242. /**
  41243. * Returns true if enough samples have been taken to completely fill the sliding window
  41244. * @return true if sample-set saturated
  41245. */
  41246. RollingAverage.prototype.isSaturated = function () {
  41247. return this._sampleCount >= this._samples.length;
  41248. };
  41249. /**
  41250. * Resets the rolling average (equivalent to 0 samples taken so far)
  41251. */
  41252. RollingAverage.prototype.reset = function () {
  41253. this.average = 0;
  41254. this.variance = 0;
  41255. this._sampleCount = 0;
  41256. this._pos = 0;
  41257. this._m2 = 0;
  41258. };
  41259. /**
  41260. * Wraps a value around the sample range boundaries
  41261. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41262. * @return Wrapped position in sample range
  41263. */
  41264. RollingAverage.prototype._wrapPosition = function (i) {
  41265. var max = this._samples.length;
  41266. return ((i % max) + max) % max;
  41267. };
  41268. return RollingAverage;
  41269. }());
  41270. BABYLON.RollingAverage = RollingAverage;
  41271. })(BABYLON || (BABYLON = {}));
  41272. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41273. var BABYLON;
  41274. (function (BABYLON) {
  41275. /**
  41276. * This groups together the common properties used for image processing either in direct forward pass
  41277. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41278. * or not.
  41279. */
  41280. var ImageProcessingConfiguration = /** @class */ (function () {
  41281. function ImageProcessingConfiguration() {
  41282. /**
  41283. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41284. */
  41285. this.colorCurves = new BABYLON.ColorCurves();
  41286. this._colorCurvesEnabled = false;
  41287. this._colorGradingEnabled = false;
  41288. this._colorGradingWithGreenDepth = true;
  41289. this._colorGradingBGR = true;
  41290. this._exposure = 1.0;
  41291. this._toneMappingEnabled = false;
  41292. this._contrast = 1.0;
  41293. /**
  41294. * Vignette stretch size.
  41295. */
  41296. this.vignetteStretch = 0;
  41297. /**
  41298. * Vignette centre X Offset.
  41299. */
  41300. this.vignetteCentreX = 0;
  41301. /**
  41302. * Vignette centre Y Offset.
  41303. */
  41304. this.vignetteCentreY = 0;
  41305. /**
  41306. * Vignette weight or intensity of the vignette effect.
  41307. */
  41308. this.vignetteWeight = 1.5;
  41309. /**
  41310. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41311. * if vignetteEnabled is set to true.
  41312. */
  41313. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41314. /**
  41315. * Camera field of view used by the Vignette effect.
  41316. */
  41317. this.vignetteCameraFov = 0.5;
  41318. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41319. this._vignetteEnabled = false;
  41320. this._applyByPostProcess = false;
  41321. this._isEnabled = true;
  41322. /**
  41323. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41324. */
  41325. this.onUpdateParameters = new BABYLON.Observable();
  41326. }
  41327. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41328. /**
  41329. * Gets wether the color curves effect is enabled.
  41330. */
  41331. get: function () {
  41332. return this._colorCurvesEnabled;
  41333. },
  41334. /**
  41335. * Sets wether the color curves effect is enabled.
  41336. */
  41337. set: function (value) {
  41338. if (this._colorCurvesEnabled === value) {
  41339. return;
  41340. }
  41341. this._colorCurvesEnabled = value;
  41342. this._updateParameters();
  41343. },
  41344. enumerable: true,
  41345. configurable: true
  41346. });
  41347. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41348. /**
  41349. * Gets wether the color grading effect is enabled.
  41350. */
  41351. get: function () {
  41352. return this._colorGradingEnabled;
  41353. },
  41354. /**
  41355. * Sets wether the color grading effect is enabled.
  41356. */
  41357. set: function (value) {
  41358. if (this._colorGradingEnabled === value) {
  41359. return;
  41360. }
  41361. this._colorGradingEnabled = value;
  41362. this._updateParameters();
  41363. },
  41364. enumerable: true,
  41365. configurable: true
  41366. });
  41367. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41368. /**
  41369. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41370. */
  41371. get: function () {
  41372. return this._colorGradingWithGreenDepth;
  41373. },
  41374. /**
  41375. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41376. */
  41377. set: function (value) {
  41378. if (this._colorGradingWithGreenDepth === value) {
  41379. return;
  41380. }
  41381. this._colorGradingWithGreenDepth = value;
  41382. this._updateParameters();
  41383. },
  41384. enumerable: true,
  41385. configurable: true
  41386. });
  41387. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41388. /**
  41389. * Gets wether the color grading texture contains BGR values.
  41390. */
  41391. get: function () {
  41392. return this._colorGradingBGR;
  41393. },
  41394. /**
  41395. * Sets wether the color grading texture contains BGR values.
  41396. */
  41397. set: function (value) {
  41398. if (this._colorGradingBGR === value) {
  41399. return;
  41400. }
  41401. this._colorGradingBGR = value;
  41402. this._updateParameters();
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41408. /**
  41409. * Gets the Exposure used in the effect.
  41410. */
  41411. get: function () {
  41412. return this._exposure;
  41413. },
  41414. /**
  41415. * Sets the Exposure used in the effect.
  41416. */
  41417. set: function (value) {
  41418. if (this._exposure === value) {
  41419. return;
  41420. }
  41421. this._exposure = value;
  41422. this._updateParameters();
  41423. },
  41424. enumerable: true,
  41425. configurable: true
  41426. });
  41427. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41428. /**
  41429. * Gets wether the tone mapping effect is enabled.
  41430. */
  41431. get: function () {
  41432. return this._toneMappingEnabled;
  41433. },
  41434. /**
  41435. * Sets wether the tone mapping effect is enabled.
  41436. */
  41437. set: function (value) {
  41438. if (this._toneMappingEnabled === value) {
  41439. return;
  41440. }
  41441. this._toneMappingEnabled = value;
  41442. this._updateParameters();
  41443. },
  41444. enumerable: true,
  41445. configurable: true
  41446. });
  41447. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41448. /**
  41449. * Gets the contrast used in the effect.
  41450. */
  41451. get: function () {
  41452. return this._contrast;
  41453. },
  41454. /**
  41455. * Sets the contrast used in the effect.
  41456. */
  41457. set: function (value) {
  41458. if (this._contrast === value) {
  41459. return;
  41460. }
  41461. this._contrast = value;
  41462. this._updateParameters();
  41463. },
  41464. enumerable: true,
  41465. configurable: true
  41466. });
  41467. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41468. /**
  41469. * Gets the vignette blend mode allowing different kind of effect.
  41470. */
  41471. get: function () {
  41472. return this._vignetteBlendMode;
  41473. },
  41474. /**
  41475. * Sets the vignette blend mode allowing different kind of effect.
  41476. */
  41477. set: function (value) {
  41478. if (this._vignetteBlendMode === value) {
  41479. return;
  41480. }
  41481. this._vignetteBlendMode = value;
  41482. this._updateParameters();
  41483. },
  41484. enumerable: true,
  41485. configurable: true
  41486. });
  41487. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41488. /**
  41489. * Gets wether the vignette effect is enabled.
  41490. */
  41491. get: function () {
  41492. return this._vignetteEnabled;
  41493. },
  41494. /**
  41495. * Sets wether the vignette effect is enabled.
  41496. */
  41497. set: function (value) {
  41498. if (this._vignetteEnabled === value) {
  41499. return;
  41500. }
  41501. this._vignetteEnabled = value;
  41502. this._updateParameters();
  41503. },
  41504. enumerable: true,
  41505. configurable: true
  41506. });
  41507. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41508. /**
  41509. * Gets wether the image processing is applied through a post process or not.
  41510. */
  41511. get: function () {
  41512. return this._applyByPostProcess;
  41513. },
  41514. /**
  41515. * Sets wether the image processing is applied through a post process or not.
  41516. */
  41517. set: function (value) {
  41518. if (this._applyByPostProcess === value) {
  41519. return;
  41520. }
  41521. this._applyByPostProcess = value;
  41522. this._updateParameters();
  41523. },
  41524. enumerable: true,
  41525. configurable: true
  41526. });
  41527. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41528. /**
  41529. * Gets wether the image processing is enabled or not.
  41530. */
  41531. get: function () {
  41532. return this._isEnabled;
  41533. },
  41534. /**
  41535. * Sets wether the image processing is enabled or not.
  41536. */
  41537. set: function (value) {
  41538. if (this._isEnabled === value) {
  41539. return;
  41540. }
  41541. this._isEnabled = value;
  41542. this._updateParameters();
  41543. },
  41544. enumerable: true,
  41545. configurable: true
  41546. });
  41547. /**
  41548. * Method called each time the image processing information changes requires to recompile the effect.
  41549. */
  41550. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41551. this.onUpdateParameters.notifyObservers(this);
  41552. };
  41553. ImageProcessingConfiguration.prototype.getClassName = function () {
  41554. return "ImageProcessingConfiguration";
  41555. };
  41556. /**
  41557. * Prepare the list of uniforms associated with the Image Processing effects.
  41558. * @param uniformsList The list of uniforms used in the effect
  41559. * @param defines the list of defines currently in use
  41560. */
  41561. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41562. if (defines.EXPOSURE) {
  41563. uniforms.push("exposureLinear");
  41564. }
  41565. if (defines.CONTRAST) {
  41566. uniforms.push("contrast");
  41567. }
  41568. if (defines.COLORGRADING) {
  41569. uniforms.push("colorTransformSettings");
  41570. }
  41571. if (defines.VIGNETTE) {
  41572. uniforms.push("vInverseScreenSize");
  41573. uniforms.push("vignetteSettings1");
  41574. uniforms.push("vignetteSettings2");
  41575. }
  41576. if (defines.COLORCURVES) {
  41577. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41578. }
  41579. };
  41580. /**
  41581. * Prepare the list of samplers associated with the Image Processing effects.
  41582. * @param uniformsList The list of uniforms used in the effect
  41583. * @param defines the list of defines currently in use
  41584. */
  41585. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41586. if (defines.COLORGRADING) {
  41587. samplersList.push("txColorTransform");
  41588. }
  41589. };
  41590. /**
  41591. * Prepare the list of defines associated to the shader.
  41592. * @param defines the list of defines to complete
  41593. */
  41594. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41595. if (forPostProcess === void 0) { forPostProcess = false; }
  41596. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41597. defines.VIGNETTE = false;
  41598. defines.TONEMAPPING = false;
  41599. defines.CONTRAST = false;
  41600. defines.EXPOSURE = false;
  41601. defines.COLORCURVES = false;
  41602. defines.COLORGRADING = false;
  41603. defines.COLORGRADING3D = false;
  41604. defines.IMAGEPROCESSING = false;
  41605. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41606. return;
  41607. }
  41608. defines.VIGNETTE = this.vignetteEnabled;
  41609. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41610. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41611. defines.TONEMAPPING = this.toneMappingEnabled;
  41612. defines.CONTRAST = (this.contrast !== 1.0);
  41613. defines.EXPOSURE = (this.exposure !== 1.0);
  41614. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41615. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41616. if (defines.COLORGRADING) {
  41617. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41618. }
  41619. else {
  41620. defines.COLORGRADING3D = false;
  41621. }
  41622. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41623. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41624. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41625. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41626. };
  41627. /**
  41628. * Returns true if all the image processing information are ready.
  41629. */
  41630. ImageProcessingConfiguration.prototype.isReady = function () {
  41631. // Color Grading texure can not be none blocking.
  41632. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41633. };
  41634. /**
  41635. * Binds the image processing to the shader.
  41636. * @param effect The effect to bind to
  41637. */
  41638. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41639. if (aspectRatio === void 0) { aspectRatio = 1; }
  41640. // Color Curves
  41641. if (this._colorCurvesEnabled && this.colorCurves) {
  41642. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41643. }
  41644. // Vignette
  41645. if (this._vignetteEnabled) {
  41646. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41647. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41648. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41649. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41650. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41651. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41652. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41653. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41654. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41655. var vignettePower = -2.0 * this.vignetteWeight;
  41656. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41657. }
  41658. // Exposure
  41659. effect.setFloat("exposureLinear", this.exposure);
  41660. // Contrast
  41661. effect.setFloat("contrast", this.contrast);
  41662. // Color transform settings
  41663. if (this.colorGradingTexture) {
  41664. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41665. var textureSize = this.colorGradingTexture.getSize().height;
  41666. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41667. 0.5 / textureSize, // textureOffset
  41668. textureSize, // textureSize
  41669. this.colorGradingTexture.level // weight
  41670. );
  41671. }
  41672. };
  41673. /**
  41674. * Clones the current image processing instance.
  41675. * @return The cloned image processing
  41676. */
  41677. ImageProcessingConfiguration.prototype.clone = function () {
  41678. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41679. };
  41680. /**
  41681. * Serializes the current image processing instance to a json representation.
  41682. * @return a JSON representation
  41683. */
  41684. ImageProcessingConfiguration.prototype.serialize = function () {
  41685. return BABYLON.SerializationHelper.Serialize(this);
  41686. };
  41687. /**
  41688. * Parses the image processing from a json representation.
  41689. * @param source the JSON source to parse
  41690. * @return The parsed image processing
  41691. */
  41692. ImageProcessingConfiguration.Parse = function (source) {
  41693. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41694. };
  41695. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41696. /**
  41697. * Used to apply the vignette as a mix with the pixel color.
  41698. */
  41699. get: function () {
  41700. return this._VIGNETTEMODE_MULTIPLY;
  41701. },
  41702. enumerable: true,
  41703. configurable: true
  41704. });
  41705. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41706. /**
  41707. * Used to apply the vignette as a replacement of the pixel color.
  41708. */
  41709. get: function () {
  41710. return this._VIGNETTEMODE_OPAQUE;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. // Static constants associated to the image processing.
  41716. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41717. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41718. __decorate([
  41719. BABYLON.serializeAsColorCurves()
  41720. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41721. __decorate([
  41722. BABYLON.serialize()
  41723. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41724. __decorate([
  41725. BABYLON.serializeAsTexture()
  41726. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41727. __decorate([
  41728. BABYLON.serialize()
  41729. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41730. __decorate([
  41731. BABYLON.serialize()
  41732. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41733. __decorate([
  41734. BABYLON.serialize()
  41735. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41736. __decorate([
  41737. BABYLON.serialize()
  41738. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41739. __decorate([
  41740. BABYLON.serialize()
  41741. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41742. __decorate([
  41743. BABYLON.serialize()
  41744. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41745. __decorate([
  41746. BABYLON.serialize()
  41747. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41748. __decorate([
  41749. BABYLON.serialize()
  41750. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41751. __decorate([
  41752. BABYLON.serialize()
  41753. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41754. __decorate([
  41755. BABYLON.serialize()
  41756. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41757. __decorate([
  41758. BABYLON.serializeAsColor4()
  41759. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41763. __decorate([
  41764. BABYLON.serialize()
  41765. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41766. __decorate([
  41767. BABYLON.serialize()
  41768. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41769. __decorate([
  41770. BABYLON.serialize()
  41771. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41772. __decorate([
  41773. BABYLON.serialize()
  41774. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41775. return ImageProcessingConfiguration;
  41776. }());
  41777. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41778. })(BABYLON || (BABYLON = {}));
  41779. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41780. var BABYLON;
  41781. (function (BABYLON) {
  41782. /**
  41783. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41784. * It can help converting any input color in a desired output one. This can then be used to create effects
  41785. * from sepia, black and white to sixties or futuristic rendering...
  41786. *
  41787. * The only supported format is currently 3dl.
  41788. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41789. */
  41790. var ColorGradingTexture = /** @class */ (function (_super) {
  41791. __extends(ColorGradingTexture, _super);
  41792. /**
  41793. * Instantiates a ColorGradingTexture from the following parameters.
  41794. *
  41795. * @param url The location of the color gradind data (currently only supporting 3dl)
  41796. * @param scene The scene the texture will be used in
  41797. */
  41798. function ColorGradingTexture(url, scene) {
  41799. var _this = _super.call(this, scene) || this;
  41800. if (!url) {
  41801. return _this;
  41802. }
  41803. _this._engine = scene.getEngine();
  41804. _this._textureMatrix = BABYLON.Matrix.Identity();
  41805. _this.name = url;
  41806. _this.url = url;
  41807. _this.hasAlpha = false;
  41808. _this.isCube = false;
  41809. _this.is3D = _this._engine.webGLVersion > 1;
  41810. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41811. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41812. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41813. _this.anisotropicFilteringLevel = 1;
  41814. _this._texture = _this._getFromCache(url, true);
  41815. if (!_this._texture) {
  41816. if (!scene.useDelayedTextureLoading) {
  41817. _this.loadTexture();
  41818. }
  41819. else {
  41820. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41821. }
  41822. }
  41823. return _this;
  41824. }
  41825. /**
  41826. * Returns the texture matrix used in most of the material.
  41827. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41828. */
  41829. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41830. return this._textureMatrix;
  41831. };
  41832. /**
  41833. * Occurs when the file being loaded is a .3dl LUT file.
  41834. */
  41835. ColorGradingTexture.prototype.load3dlTexture = function () {
  41836. var engine = this._engine;
  41837. var texture;
  41838. if (engine.webGLVersion === 1) {
  41839. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41840. }
  41841. else {
  41842. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41843. }
  41844. this._texture = texture;
  41845. var callback = function (text) {
  41846. if (typeof text !== "string") {
  41847. return;
  41848. }
  41849. var data = null;
  41850. var tempData = null;
  41851. var line;
  41852. var lines = text.split('\n');
  41853. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41854. var maxColor = 0;
  41855. for (var i = 0; i < lines.length; i++) {
  41856. line = lines[i];
  41857. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41858. continue;
  41859. if (line.indexOf('#') === 0)
  41860. continue;
  41861. var words = line.split(" ");
  41862. if (size === 0) {
  41863. // Number of space + one
  41864. size = words.length;
  41865. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41866. tempData = new Float32Array(size * size * size * 4);
  41867. continue;
  41868. }
  41869. if (size != 0) {
  41870. var r = Math.max(parseInt(words[0]), 0);
  41871. var g = Math.max(parseInt(words[1]), 0);
  41872. var b = Math.max(parseInt(words[2]), 0);
  41873. maxColor = Math.max(r, maxColor);
  41874. maxColor = Math.max(g, maxColor);
  41875. maxColor = Math.max(b, maxColor);
  41876. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41877. if (tempData) {
  41878. tempData[pixelStorageIndex + 0] = r;
  41879. tempData[pixelStorageIndex + 1] = g;
  41880. tempData[pixelStorageIndex + 2] = b;
  41881. }
  41882. pixelIndexSlice++;
  41883. if (pixelIndexSlice % size == 0) {
  41884. pixelIndexH++;
  41885. pixelIndexSlice = 0;
  41886. if (pixelIndexH % size == 0) {
  41887. pixelIndexW++;
  41888. pixelIndexH = 0;
  41889. }
  41890. }
  41891. }
  41892. }
  41893. if (tempData && data) {
  41894. for (var i = 0; i < tempData.length; i++) {
  41895. if (i > 0 && (i + 1) % 4 === 0) {
  41896. data[i] = 255;
  41897. }
  41898. else {
  41899. var value = tempData[i];
  41900. data[i] = (value / maxColor * 255);
  41901. }
  41902. }
  41903. }
  41904. if (texture.is3D) {
  41905. texture.updateSize(size, size, size);
  41906. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41907. }
  41908. else {
  41909. texture.updateSize(size * size, size);
  41910. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41911. }
  41912. };
  41913. var scene = this.getScene();
  41914. if (scene) {
  41915. scene._loadFile(this.url, callback);
  41916. }
  41917. else {
  41918. this._engine._loadFile(this.url, callback);
  41919. }
  41920. return this._texture;
  41921. };
  41922. /**
  41923. * Starts the loading process of the texture.
  41924. */
  41925. ColorGradingTexture.prototype.loadTexture = function () {
  41926. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41927. this.load3dlTexture();
  41928. }
  41929. };
  41930. /**
  41931. * Clones the color gradind texture.
  41932. */
  41933. ColorGradingTexture.prototype.clone = function () {
  41934. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41935. // Base texture
  41936. newTexture.level = this.level;
  41937. return newTexture;
  41938. };
  41939. /**
  41940. * Called during delayed load for textures.
  41941. */
  41942. ColorGradingTexture.prototype.delayLoad = function () {
  41943. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41944. return;
  41945. }
  41946. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41947. this._texture = this._getFromCache(this.url, true);
  41948. if (!this._texture) {
  41949. this.loadTexture();
  41950. }
  41951. };
  41952. /**
  41953. * Parses a color grading texture serialized by Babylon.
  41954. * @param parsedTexture The texture information being parsedTexture
  41955. * @param scene The scene to load the texture in
  41956. * @param rootUrl The root url of the data assets to load
  41957. * @return A color gradind texture
  41958. */
  41959. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41960. var texture = null;
  41961. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41962. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41963. texture.name = parsedTexture.name;
  41964. texture.level = parsedTexture.level;
  41965. }
  41966. return texture;
  41967. };
  41968. /**
  41969. * Serializes the LUT texture to json format.
  41970. */
  41971. ColorGradingTexture.prototype.serialize = function () {
  41972. if (!this.name) {
  41973. return null;
  41974. }
  41975. var serializationObject = {};
  41976. serializationObject.name = this.name;
  41977. serializationObject.level = this.level;
  41978. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41979. return serializationObject;
  41980. };
  41981. /**
  41982. * Empty line regex stored for GC.
  41983. */
  41984. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41985. return ColorGradingTexture;
  41986. }(BABYLON.BaseTexture));
  41987. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41988. })(BABYLON || (BABYLON = {}));
  41989. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41990. var BABYLON;
  41991. (function (BABYLON) {
  41992. /**
  41993. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41994. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41995. * 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;
  41996. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41997. */
  41998. var ColorCurves = /** @class */ (function () {
  41999. function ColorCurves() {
  42000. this._dirty = true;
  42001. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  42002. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  42003. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42004. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  42005. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42006. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  42007. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  42008. this._globalHue = 30;
  42009. this._globalDensity = 0;
  42010. this._globalSaturation = 0;
  42011. this._globalExposure = 0;
  42012. this._highlightsHue = 30;
  42013. this._highlightsDensity = 0;
  42014. this._highlightsSaturation = 0;
  42015. this._highlightsExposure = 0;
  42016. this._midtonesHue = 30;
  42017. this._midtonesDensity = 0;
  42018. this._midtonesSaturation = 0;
  42019. this._midtonesExposure = 0;
  42020. this._shadowsHue = 30;
  42021. this._shadowsDensity = 0;
  42022. this._shadowsSaturation = 0;
  42023. this._shadowsExposure = 0;
  42024. }
  42025. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  42026. /**
  42027. * Gets the global Hue value.
  42028. * 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).
  42029. */
  42030. get: function () {
  42031. return this._globalHue;
  42032. },
  42033. /**
  42034. * Sets the global Hue value.
  42035. * 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).
  42036. */
  42037. set: function (value) {
  42038. this._globalHue = value;
  42039. this._dirty = true;
  42040. },
  42041. enumerable: true,
  42042. configurable: true
  42043. });
  42044. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  42045. /**
  42046. * Gets the global Density value.
  42047. * 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.
  42048. * Values less than zero provide a filter of opposite hue.
  42049. */
  42050. get: function () {
  42051. return this._globalDensity;
  42052. },
  42053. /**
  42054. * Sets the global Density value.
  42055. * 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.
  42056. * Values less than zero provide a filter of opposite hue.
  42057. */
  42058. set: function (value) {
  42059. this._globalDensity = value;
  42060. this._dirty = true;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  42066. /**
  42067. * Gets the global Saturation value.
  42068. * 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.
  42069. */
  42070. get: function () {
  42071. return this._globalSaturation;
  42072. },
  42073. /**
  42074. * Sets the global Saturation value.
  42075. * 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.
  42076. */
  42077. set: function (value) {
  42078. this._globalSaturation = value;
  42079. this._dirty = true;
  42080. },
  42081. enumerable: true,
  42082. configurable: true
  42083. });
  42084. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42085. /**
  42086. * Gets the global Exposure value.
  42087. * 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.
  42088. */
  42089. get: function () {
  42090. return this._globalExposure;
  42091. },
  42092. /**
  42093. * Sets the global Exposure value.
  42094. * 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.
  42095. */
  42096. set: function (value) {
  42097. this._globalExposure = value;
  42098. this._dirty = true;
  42099. },
  42100. enumerable: true,
  42101. configurable: true
  42102. });
  42103. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42104. /**
  42105. * Gets the highlights Hue value.
  42106. * 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).
  42107. */
  42108. get: function () {
  42109. return this._highlightsHue;
  42110. },
  42111. /**
  42112. * Sets the highlights Hue value.
  42113. * 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).
  42114. */
  42115. set: function (value) {
  42116. this._highlightsHue = value;
  42117. this._dirty = true;
  42118. },
  42119. enumerable: true,
  42120. configurable: true
  42121. });
  42122. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42123. /**
  42124. * Gets the highlights Density value.
  42125. * 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.
  42126. * Values less than zero provide a filter of opposite hue.
  42127. */
  42128. get: function () {
  42129. return this._highlightsDensity;
  42130. },
  42131. /**
  42132. * Sets the highlights Density value.
  42133. * 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.
  42134. * Values less than zero provide a filter of opposite hue.
  42135. */
  42136. set: function (value) {
  42137. this._highlightsDensity = value;
  42138. this._dirty = true;
  42139. },
  42140. enumerable: true,
  42141. configurable: true
  42142. });
  42143. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42144. /**
  42145. * Gets the highlights Saturation value.
  42146. * 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.
  42147. */
  42148. get: function () {
  42149. return this._highlightsSaturation;
  42150. },
  42151. /**
  42152. * Sets the highlights Saturation value.
  42153. * 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.
  42154. */
  42155. set: function (value) {
  42156. this._highlightsSaturation = value;
  42157. this._dirty = true;
  42158. },
  42159. enumerable: true,
  42160. configurable: true
  42161. });
  42162. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42163. /**
  42164. * Gets the highlights Exposure value.
  42165. * 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.
  42166. */
  42167. get: function () {
  42168. return this._highlightsExposure;
  42169. },
  42170. /**
  42171. * Sets the highlights Exposure value.
  42172. * 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.
  42173. */
  42174. set: function (value) {
  42175. this._highlightsExposure = value;
  42176. this._dirty = true;
  42177. },
  42178. enumerable: true,
  42179. configurable: true
  42180. });
  42181. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42182. /**
  42183. * Gets the midtones Hue value.
  42184. * 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).
  42185. */
  42186. get: function () {
  42187. return this._midtonesHue;
  42188. },
  42189. /**
  42190. * Sets the midtones Hue value.
  42191. * 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).
  42192. */
  42193. set: function (value) {
  42194. this._midtonesHue = value;
  42195. this._dirty = true;
  42196. },
  42197. enumerable: true,
  42198. configurable: true
  42199. });
  42200. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42201. /**
  42202. * Gets the midtones Density value.
  42203. * 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.
  42204. * Values less than zero provide a filter of opposite hue.
  42205. */
  42206. get: function () {
  42207. return this._midtonesDensity;
  42208. },
  42209. /**
  42210. * Sets the midtones Density value.
  42211. * 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.
  42212. * Values less than zero provide a filter of opposite hue.
  42213. */
  42214. set: function (value) {
  42215. this._midtonesDensity = value;
  42216. this._dirty = true;
  42217. },
  42218. enumerable: true,
  42219. configurable: true
  42220. });
  42221. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42222. /**
  42223. * Gets the midtones Saturation value.
  42224. * 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.
  42225. */
  42226. get: function () {
  42227. return this._midtonesSaturation;
  42228. },
  42229. /**
  42230. * Sets the midtones Saturation value.
  42231. * 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.
  42232. */
  42233. set: function (value) {
  42234. this._midtonesSaturation = value;
  42235. this._dirty = true;
  42236. },
  42237. enumerable: true,
  42238. configurable: true
  42239. });
  42240. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42241. /**
  42242. * Gets the midtones Exposure value.
  42243. * 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.
  42244. */
  42245. get: function () {
  42246. return this._midtonesExposure;
  42247. },
  42248. /**
  42249. * Sets the midtones Exposure value.
  42250. * 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.
  42251. */
  42252. set: function (value) {
  42253. this._midtonesExposure = value;
  42254. this._dirty = true;
  42255. },
  42256. enumerable: true,
  42257. configurable: true
  42258. });
  42259. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42260. /**
  42261. * Gets the shadows Hue value.
  42262. * 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).
  42263. */
  42264. get: function () {
  42265. return this._shadowsHue;
  42266. },
  42267. /**
  42268. * Sets the shadows Hue value.
  42269. * 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).
  42270. */
  42271. set: function (value) {
  42272. this._shadowsHue = value;
  42273. this._dirty = true;
  42274. },
  42275. enumerable: true,
  42276. configurable: true
  42277. });
  42278. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42279. /**
  42280. * Gets the shadows Density value.
  42281. * 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.
  42282. * Values less than zero provide a filter of opposite hue.
  42283. */
  42284. get: function () {
  42285. return this._shadowsDensity;
  42286. },
  42287. /**
  42288. * Sets the shadows Density value.
  42289. * 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.
  42290. * Values less than zero provide a filter of opposite hue.
  42291. */
  42292. set: function (value) {
  42293. this._shadowsDensity = value;
  42294. this._dirty = true;
  42295. },
  42296. enumerable: true,
  42297. configurable: true
  42298. });
  42299. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42300. /**
  42301. * Gets the shadows Saturation value.
  42302. * 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.
  42303. */
  42304. get: function () {
  42305. return this._shadowsSaturation;
  42306. },
  42307. /**
  42308. * Sets the shadows Saturation value.
  42309. * 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.
  42310. */
  42311. set: function (value) {
  42312. this._shadowsSaturation = value;
  42313. this._dirty = true;
  42314. },
  42315. enumerable: true,
  42316. configurable: true
  42317. });
  42318. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42319. /**
  42320. * Gets the shadows Exposure value.
  42321. * 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.
  42322. */
  42323. get: function () {
  42324. return this._shadowsExposure;
  42325. },
  42326. /**
  42327. * Sets the shadows Exposure value.
  42328. * 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.
  42329. */
  42330. set: function (value) {
  42331. this._shadowsExposure = value;
  42332. this._dirty = true;
  42333. },
  42334. enumerable: true,
  42335. configurable: true
  42336. });
  42337. ColorCurves.prototype.getClassName = function () {
  42338. return "ColorCurves";
  42339. };
  42340. /**
  42341. * Binds the color curves to the shader.
  42342. * @param colorCurves The color curve to bind
  42343. * @param effect The effect to bind to
  42344. */
  42345. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42346. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42347. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42348. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42349. if (colorCurves._dirty) {
  42350. colorCurves._dirty = false;
  42351. // Fill in global info.
  42352. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42353. // Compute highlights info.
  42354. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42355. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42356. // Compute midtones info.
  42357. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42358. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42359. // Compute shadows info.
  42360. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42361. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42362. // Compute deltas (neutral is midtones).
  42363. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42364. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42365. }
  42366. if (effect) {
  42367. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42368. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42369. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42370. }
  42371. };
  42372. /**
  42373. * Prepare the list of uniforms associated with the ColorCurves effects.
  42374. * @param uniformsList The list of uniforms used in the effect
  42375. */
  42376. ColorCurves.PrepareUniforms = function (uniformsList) {
  42377. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42378. };
  42379. /**
  42380. * Returns color grading data based on a hue, density, saturation and exposure value.
  42381. * @param filterHue The hue of the color filter.
  42382. * @param filterDensity The density of the color filter.
  42383. * @param saturation The saturation.
  42384. * @param exposure The exposure.
  42385. * @param result The result data container.
  42386. */
  42387. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42388. if (hue == null) {
  42389. return;
  42390. }
  42391. hue = ColorCurves.clamp(hue, 0, 360);
  42392. density = ColorCurves.clamp(density, -100, 100);
  42393. saturation = ColorCurves.clamp(saturation, -100, 100);
  42394. exposure = ColorCurves.clamp(exposure, -100, 100);
  42395. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42396. // so that the maximum filter density is only 50% control. This provides fine control
  42397. // for small values and reasonable range.
  42398. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42399. density *= 0.5;
  42400. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42401. if (density < 0) {
  42402. density *= -1;
  42403. hue = (hue + 180) % 360;
  42404. }
  42405. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42406. result.scaleToRef(2, result);
  42407. result.a = 1 + 0.01 * saturation;
  42408. };
  42409. /**
  42410. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42411. * @param value The input slider value in range [-100,100].
  42412. * @returns Adjusted value.
  42413. */
  42414. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42415. value /= 100;
  42416. var x = Math.abs(value);
  42417. x = Math.pow(x, 2);
  42418. if (value < 0) {
  42419. x *= -1;
  42420. }
  42421. x *= 100;
  42422. return x;
  42423. };
  42424. /**
  42425. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42426. * @param hue The hue (H) input.
  42427. * @param saturation The saturation (S) input.
  42428. * @param brightness The brightness (B) input.
  42429. * @result An RGBA color represented as Vector4.
  42430. */
  42431. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42432. var h = ColorCurves.clamp(hue, 0, 360);
  42433. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42434. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42435. if (s === 0) {
  42436. result.r = v;
  42437. result.g = v;
  42438. result.b = v;
  42439. }
  42440. else {
  42441. // sector 0 to 5
  42442. h /= 60;
  42443. var i = Math.floor(h);
  42444. // fractional part of h
  42445. var f = h - i;
  42446. var p = v * (1 - s);
  42447. var q = v * (1 - s * f);
  42448. var t = v * (1 - s * (1 - f));
  42449. switch (i) {
  42450. case 0:
  42451. result.r = v;
  42452. result.g = t;
  42453. result.b = p;
  42454. break;
  42455. case 1:
  42456. result.r = q;
  42457. result.g = v;
  42458. result.b = p;
  42459. break;
  42460. case 2:
  42461. result.r = p;
  42462. result.g = v;
  42463. result.b = t;
  42464. break;
  42465. case 3:
  42466. result.r = p;
  42467. result.g = q;
  42468. result.b = v;
  42469. break;
  42470. case 4:
  42471. result.r = t;
  42472. result.g = p;
  42473. result.b = v;
  42474. break;
  42475. default: // case 5:
  42476. result.r = v;
  42477. result.g = p;
  42478. result.b = q;
  42479. break;
  42480. }
  42481. }
  42482. result.a = 1;
  42483. };
  42484. /**
  42485. * Returns a value clamped between min and max
  42486. * @param value The value to clamp
  42487. * @param min The minimum of value
  42488. * @param max The maximum of value
  42489. * @returns The clamped value.
  42490. */
  42491. ColorCurves.clamp = function (value, min, max) {
  42492. return Math.min(Math.max(value, min), max);
  42493. };
  42494. /**
  42495. * Clones the current color curve instance.
  42496. * @return The cloned curves
  42497. */
  42498. ColorCurves.prototype.clone = function () {
  42499. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42500. };
  42501. /**
  42502. * Serializes the current color curve instance to a json representation.
  42503. * @return a JSON representation
  42504. */
  42505. ColorCurves.prototype.serialize = function () {
  42506. return BABYLON.SerializationHelper.Serialize(this);
  42507. };
  42508. /**
  42509. * Parses the color curve from a json representation.
  42510. * @param source the JSON source to parse
  42511. * @return The parsed curves
  42512. */
  42513. ColorCurves.Parse = function (source) {
  42514. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42515. };
  42516. __decorate([
  42517. BABYLON.serialize()
  42518. ], ColorCurves.prototype, "_globalHue", void 0);
  42519. __decorate([
  42520. BABYLON.serialize()
  42521. ], ColorCurves.prototype, "_globalDensity", void 0);
  42522. __decorate([
  42523. BABYLON.serialize()
  42524. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42525. __decorate([
  42526. BABYLON.serialize()
  42527. ], ColorCurves.prototype, "_globalExposure", void 0);
  42528. __decorate([
  42529. BABYLON.serialize()
  42530. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42531. __decorate([
  42532. BABYLON.serialize()
  42533. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42534. __decorate([
  42535. BABYLON.serialize()
  42536. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42537. __decorate([
  42538. BABYLON.serialize()
  42539. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42540. __decorate([
  42541. BABYLON.serialize()
  42542. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42543. __decorate([
  42544. BABYLON.serialize()
  42545. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42546. __decorate([
  42547. BABYLON.serialize()
  42548. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42549. __decorate([
  42550. BABYLON.serialize()
  42551. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42552. return ColorCurves;
  42553. }());
  42554. BABYLON.ColorCurves = ColorCurves;
  42555. })(BABYLON || (BABYLON = {}));
  42556. //# sourceMappingURL=babylon.colorCurves.js.map
  42557. //# sourceMappingURL=babylon.behavior.js.map
  42558. var BABYLON;
  42559. (function (BABYLON) {
  42560. /**
  42561. * "Static Class" containing the most commonly used helper while dealing with material for
  42562. * rendering purpose.
  42563. *
  42564. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42565. *
  42566. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42567. */
  42568. var MaterialHelper = /** @class */ (function () {
  42569. function MaterialHelper() {
  42570. }
  42571. /**
  42572. * Bind the current view position to an effect.
  42573. * @param effect The effect to be bound
  42574. * @param scene The scene the eyes position is used from
  42575. */
  42576. MaterialHelper.BindEyePosition = function (effect, scene) {
  42577. if (scene._forcedViewPosition) {
  42578. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42579. return;
  42580. }
  42581. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42582. };
  42583. /**
  42584. * Helps preparing the defines values about the UVs in used in the effect.
  42585. * UVs are shared as much as we can accross chanels in the shaders.
  42586. * @param texture The texture we are preparing the UVs for
  42587. * @param defines The defines to update
  42588. * @param key The chanel key "diffuse", "specular"... used in the shader
  42589. */
  42590. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42591. defines._needUVs = true;
  42592. defines[key] = true;
  42593. if (texture.getTextureMatrix().isIdentity(true)) {
  42594. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42595. if (texture.coordinatesIndex === 0) {
  42596. defines["MAINUV1"] = true;
  42597. }
  42598. else {
  42599. defines["MAINUV2"] = true;
  42600. }
  42601. }
  42602. else {
  42603. defines[key + "DIRECTUV"] = 0;
  42604. }
  42605. };
  42606. /**
  42607. * Binds a texture matrix value to its corrsponding uniform
  42608. * @param texture The texture to bind the matrix for
  42609. * @param uniformBuffer The uniform buffer receivin the data
  42610. * @param key The chanel key "diffuse", "specular"... used in the shader
  42611. */
  42612. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42613. var matrix = texture.getTextureMatrix();
  42614. if (!matrix.isIdentity(true)) {
  42615. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42616. }
  42617. };
  42618. /**
  42619. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42620. * @param mesh defines the current mesh
  42621. * @param scene defines the current scene
  42622. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42623. * @param pointsCloud defines if point cloud rendering has to be turned on
  42624. * @param fogEnabled defines if fog has to be turned on
  42625. * @param alphaTest defines if alpha testing has to be turned on
  42626. * @param defines defines the current list of defines
  42627. */
  42628. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42629. if (defines._areMiscDirty) {
  42630. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42631. defines["POINTSIZE"] = pointsCloud;
  42632. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42633. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42634. defines["ALPHATEST"] = alphaTest;
  42635. }
  42636. };
  42637. /**
  42638. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42639. * @param scene defines the current scene
  42640. * @param engine defines the current engine
  42641. * @param defines specifies the list of active defines
  42642. * @param useInstances defines if instances have to be turned on
  42643. * @param useClipPlane defines if clip plane have to be turned on
  42644. */
  42645. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42646. if (useClipPlane === void 0) { useClipPlane = null; }
  42647. var changed = false;
  42648. if (useClipPlane == null) {
  42649. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42650. }
  42651. if (defines["CLIPPLANE"] !== useClipPlane) {
  42652. defines["CLIPPLANE"] = useClipPlane;
  42653. changed = true;
  42654. }
  42655. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42656. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42657. changed = true;
  42658. }
  42659. if (defines["INSTANCES"] !== useInstances) {
  42660. defines["INSTANCES"] = useInstances;
  42661. changed = true;
  42662. }
  42663. if (changed) {
  42664. defines.markAsUnprocessed();
  42665. }
  42666. };
  42667. /**
  42668. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42669. * @param mesh The mesh containing the geometry data we will draw
  42670. * @param defines The defines to update
  42671. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42672. * @param useBones Precise whether bones should be used or not (override mesh info)
  42673. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42674. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42675. * @returns false if defines are considered not dirty and have not been checked
  42676. */
  42677. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42678. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42679. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42680. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42681. return false;
  42682. }
  42683. defines._normals = defines._needNormals;
  42684. defines._uvs = defines._needUVs;
  42685. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42686. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42687. defines["TANGENT"] = true;
  42688. }
  42689. if (defines._needUVs) {
  42690. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42691. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42692. }
  42693. else {
  42694. defines["UV1"] = false;
  42695. defines["UV2"] = false;
  42696. }
  42697. if (useVertexColor) {
  42698. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42699. defines["VERTEXCOLOR"] = hasVertexColors;
  42700. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42701. }
  42702. if (useBones) {
  42703. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42704. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42705. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42706. }
  42707. else {
  42708. defines["NUM_BONE_INFLUENCERS"] = 0;
  42709. defines["BonesPerMesh"] = 0;
  42710. }
  42711. }
  42712. if (useMorphTargets) {
  42713. var manager = mesh.morphTargetManager;
  42714. if (manager) {
  42715. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42716. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42717. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42718. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42719. }
  42720. else {
  42721. defines["MORPHTARGETS_TANGENT"] = false;
  42722. defines["MORPHTARGETS_NORMAL"] = false;
  42723. defines["MORPHTARGETS"] = false;
  42724. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42725. }
  42726. }
  42727. return true;
  42728. };
  42729. /**
  42730. * Prepares the defines related to the light information passed in parameter
  42731. * @param scene The scene we are intending to draw
  42732. * @param mesh The mesh the effect is compiling for
  42733. * @param defines The defines to update
  42734. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42735. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42736. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42737. * @returns true if normals will be required for the rest of the effect
  42738. */
  42739. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42740. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42741. if (disableLighting === void 0) { disableLighting = false; }
  42742. if (!defines._areLightsDirty) {
  42743. return defines._needNormals;
  42744. }
  42745. var lightIndex = 0;
  42746. var needNormals = false;
  42747. var needRebuild = false;
  42748. var lightmapMode = false;
  42749. var shadowEnabled = false;
  42750. var specularEnabled = false;
  42751. if (scene.lightsEnabled && !disableLighting) {
  42752. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42753. var light = _a[_i];
  42754. needNormals = true;
  42755. if (defines["LIGHT" + lightIndex] === undefined) {
  42756. needRebuild = true;
  42757. }
  42758. defines["LIGHT" + lightIndex] = true;
  42759. defines["SPOTLIGHT" + lightIndex] = false;
  42760. defines["HEMILIGHT" + lightIndex] = false;
  42761. defines["POINTLIGHT" + lightIndex] = false;
  42762. defines["DIRLIGHT" + lightIndex] = false;
  42763. var type;
  42764. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42765. type = "SPOTLIGHT" + lightIndex;
  42766. var spotLight = light;
  42767. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42768. }
  42769. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42770. type = "HEMILIGHT" + lightIndex;
  42771. }
  42772. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42773. type = "POINTLIGHT" + lightIndex;
  42774. }
  42775. else {
  42776. type = "DIRLIGHT" + lightIndex;
  42777. }
  42778. defines[type] = true;
  42779. // Specular
  42780. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42781. specularEnabled = true;
  42782. }
  42783. // Shadows
  42784. defines["SHADOW" + lightIndex] = false;
  42785. defines["SHADOWPCF" + lightIndex] = false;
  42786. defines["SHADOWPCSS" + lightIndex] = false;
  42787. defines["SHADOWPOISSON" + lightIndex] = false;
  42788. defines["SHADOWESM" + lightIndex] = false;
  42789. defines["SHADOWCUBE" + lightIndex] = false;
  42790. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42791. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42792. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42793. var shadowGenerator = light.getShadowGenerator();
  42794. if (shadowGenerator) {
  42795. shadowEnabled = true;
  42796. shadowGenerator.prepareDefines(defines, lightIndex);
  42797. }
  42798. }
  42799. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42800. lightmapMode = true;
  42801. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42802. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42803. }
  42804. else {
  42805. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42806. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42807. }
  42808. lightIndex++;
  42809. if (lightIndex === maxSimultaneousLights)
  42810. break;
  42811. }
  42812. }
  42813. defines["SPECULARTERM"] = specularEnabled;
  42814. defines["SHADOWS"] = shadowEnabled;
  42815. // Resetting all other lights if any
  42816. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42817. if (defines["LIGHT" + index] !== undefined) {
  42818. defines["LIGHT" + index] = false;
  42819. defines["HEMILIGHT" + lightIndex] = false;
  42820. defines["POINTLIGHT" + lightIndex] = false;
  42821. defines["DIRLIGHT" + lightIndex] = false;
  42822. defines["SPOTLIGHT" + lightIndex] = false;
  42823. defines["SHADOW" + lightIndex] = false;
  42824. }
  42825. }
  42826. var caps = scene.getEngine().getCaps();
  42827. if (defines["SHADOWFLOAT"] === undefined) {
  42828. needRebuild = true;
  42829. }
  42830. defines["SHADOWFLOAT"] = shadowEnabled &&
  42831. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42832. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42833. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42834. if (needRebuild) {
  42835. defines.rebuild();
  42836. }
  42837. return needNormals;
  42838. };
  42839. /**
  42840. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42841. * that won t be acctive due to defines being turned off.
  42842. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42843. * @param samplersList The samplers list
  42844. * @param defines The defines helping in the list generation
  42845. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42846. */
  42847. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42848. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42849. var uniformsList;
  42850. var uniformBuffersList = null;
  42851. if (uniformsListOrOptions.uniformsNames) {
  42852. var options = uniformsListOrOptions;
  42853. uniformsList = options.uniformsNames;
  42854. uniformBuffersList = options.uniformBuffersNames;
  42855. samplersList = options.samplers;
  42856. defines = options.defines;
  42857. maxSimultaneousLights = options.maxSimultaneousLights;
  42858. }
  42859. else {
  42860. uniformsList = uniformsListOrOptions;
  42861. if (!samplersList) {
  42862. samplersList = [];
  42863. }
  42864. }
  42865. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42866. if (!defines["LIGHT" + lightIndex]) {
  42867. break;
  42868. }
  42869. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42870. if (uniformBuffersList) {
  42871. uniformBuffersList.push("Light" + lightIndex);
  42872. }
  42873. samplersList.push("shadowSampler" + lightIndex);
  42874. samplersList.push("depthSampler" + lightIndex);
  42875. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42876. samplersList.push("projectionLightSampler" + lightIndex);
  42877. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42878. }
  42879. }
  42880. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42881. uniformsList.push("morphTargetInfluences");
  42882. }
  42883. };
  42884. /**
  42885. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42886. * @param defines The defines to update while falling back
  42887. * @param fallbacks The authorized effect fallbacks
  42888. * @param maxSimultaneousLights The maximum number of lights allowed
  42889. * @param rank the current rank of the Effect
  42890. * @returns The newly affected rank
  42891. */
  42892. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42893. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42894. if (rank === void 0) { rank = 0; }
  42895. var lightFallbackRank = 0;
  42896. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42897. if (!defines["LIGHT" + lightIndex]) {
  42898. break;
  42899. }
  42900. if (lightIndex > 0) {
  42901. lightFallbackRank = rank + lightIndex;
  42902. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42903. }
  42904. if (!defines["SHADOWS"]) {
  42905. if (defines["SHADOW" + lightIndex]) {
  42906. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42907. }
  42908. if (defines["SHADOWPCF" + lightIndex]) {
  42909. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42910. }
  42911. if (defines["SHADOWPCSS" + lightIndex]) {
  42912. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42913. }
  42914. if (defines["SHADOWPOISSON" + lightIndex]) {
  42915. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42916. }
  42917. if (defines["SHADOWESM" + lightIndex]) {
  42918. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42919. }
  42920. }
  42921. }
  42922. return lightFallbackRank++;
  42923. };
  42924. /**
  42925. * Prepares the list of attributes required for morph targets according to the effect defines.
  42926. * @param attribs The current list of supported attribs
  42927. * @param mesh The mesh to prepare the morph targets attributes for
  42928. * @param defines The current Defines of the effect
  42929. */
  42930. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42931. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42932. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42933. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42934. var manager = mesh.morphTargetManager;
  42935. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42936. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42937. for (var index = 0; index < influencers; index++) {
  42938. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42939. if (normal) {
  42940. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42941. }
  42942. if (tangent) {
  42943. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42944. }
  42945. if (attribs.length > maxAttributesCount) {
  42946. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42947. }
  42948. }
  42949. }
  42950. };
  42951. /**
  42952. * Prepares the list of attributes required for bones according to the effect defines.
  42953. * @param attribs The current list of supported attribs
  42954. * @param mesh The mesh to prepare the bones attributes for
  42955. * @param defines The current Defines of the effect
  42956. * @param fallbacks The current efffect fallback strategy
  42957. */
  42958. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42959. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42960. fallbacks.addCPUSkinningFallback(0, mesh);
  42961. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42962. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42963. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42964. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42965. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42966. }
  42967. }
  42968. };
  42969. /**
  42970. * Prepares the list of attributes required for instances according to the effect defines.
  42971. * @param attribs The current list of supported attribs
  42972. * @param defines The current Defines of the effect
  42973. */
  42974. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42975. if (defines["INSTANCES"]) {
  42976. attribs.push("world0");
  42977. attribs.push("world1");
  42978. attribs.push("world2");
  42979. attribs.push("world3");
  42980. }
  42981. };
  42982. /**
  42983. * Binds the light shadow information to the effect for the given mesh.
  42984. * @param light The light containing the generator
  42985. * @param scene The scene the lights belongs to
  42986. * @param mesh The mesh we are binding the information to render
  42987. * @param lightIndex The light index in the effect used to render the mesh
  42988. * @param effect The effect we are binding the data to
  42989. */
  42990. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42991. if (light.shadowEnabled && mesh.receiveShadows) {
  42992. var shadowGenerator = light.getShadowGenerator();
  42993. if (shadowGenerator) {
  42994. shadowGenerator.bindShadowLight(lightIndex, effect);
  42995. }
  42996. }
  42997. };
  42998. /**
  42999. * Binds the light information to the effect.
  43000. * @param light The light containing the generator
  43001. * @param effect The effect we are binding the data to
  43002. * @param lightIndex The light index in the effect used to render
  43003. */
  43004. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43005. light.transferToEffect(effect, lightIndex + "");
  43006. };
  43007. /**
  43008. * Binds the lights information from the scene to the effect for the given mesh.
  43009. * @param scene The scene the lights belongs to
  43010. * @param mesh The mesh we are binding the information to render
  43011. * @param effect The effect we are binding the data to
  43012. * @param defines The generated defines for the effect
  43013. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43014. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43015. */
  43016. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43017. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43018. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43019. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43020. for (var i = 0; i < len; i++) {
  43021. var light = mesh._lightSources[i];
  43022. var iAsString = i.toString();
  43023. var scaledIntensity = light.getScaledIntensity();
  43024. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43025. MaterialHelper.BindLightProperties(light, effect, i);
  43026. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43027. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43028. if (defines["SPECULARTERM"]) {
  43029. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43030. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43031. }
  43032. // Shadows
  43033. if (scene.shadowsEnabled) {
  43034. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43035. }
  43036. light._uniformBuffer.update();
  43037. }
  43038. };
  43039. /**
  43040. * Binds the fog information from the scene to the effect for the given mesh.
  43041. * @param scene The scene the lights belongs to
  43042. * @param mesh The mesh we are binding the information to render
  43043. * @param effect The effect we are binding the data to
  43044. */
  43045. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  43046. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43047. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43048. effect.setColor3("vFogColor", scene.fogColor);
  43049. }
  43050. };
  43051. /**
  43052. * Binds the bones information from the mesh to the effect.
  43053. * @param mesh The mesh we are binding the information to render
  43054. * @param effect The effect we are binding the data to
  43055. */
  43056. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43057. if (!effect || !mesh) {
  43058. return;
  43059. }
  43060. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43061. mesh.computeBonesUsingShaders = false;
  43062. }
  43063. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43064. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43065. if (matrices) {
  43066. effect.setMatrices("mBones", matrices);
  43067. }
  43068. }
  43069. };
  43070. /**
  43071. * Binds the morph targets information from the mesh to the effect.
  43072. * @param abstractMesh The mesh we are binding the information to render
  43073. * @param effect The effect we are binding the data to
  43074. */
  43075. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43076. var manager = abstractMesh.morphTargetManager;
  43077. if (!abstractMesh || !manager) {
  43078. return;
  43079. }
  43080. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43081. };
  43082. /**
  43083. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43084. * @param defines The generated defines used in the effect
  43085. * @param effect The effect we are binding the data to
  43086. * @param scene The scene we are willing to render with logarithmic scale for
  43087. */
  43088. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43089. if (defines["LOGARITHMICDEPTH"]) {
  43090. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43091. }
  43092. };
  43093. /**
  43094. * Binds the clip plane information from the scene to the effect.
  43095. * @param scene The scene the clip plane information are extracted from
  43096. * @param effect The effect we are binding the data to
  43097. */
  43098. MaterialHelper.BindClipPlane = function (effect, scene) {
  43099. if (scene.clipPlane) {
  43100. var clipPlane = scene.clipPlane;
  43101. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43102. }
  43103. };
  43104. return MaterialHelper;
  43105. }());
  43106. BABYLON.MaterialHelper = MaterialHelper;
  43107. })(BABYLON || (BABYLON = {}));
  43108. //# sourceMappingURL=babylon.materialHelper.js.map
  43109. var BABYLON;
  43110. (function (BABYLON) {
  43111. var PushMaterial = /** @class */ (function (_super) {
  43112. __extends(PushMaterial, _super);
  43113. function PushMaterial(name, scene) {
  43114. var _this = _super.call(this, name, scene) || this;
  43115. _this._normalMatrix = new BABYLON.Matrix();
  43116. _this.storeEffectOnSubMeshes = true;
  43117. return _this;
  43118. }
  43119. PushMaterial.prototype.getEffect = function () {
  43120. return this._activeEffect;
  43121. };
  43122. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43123. if (!mesh) {
  43124. return false;
  43125. }
  43126. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43127. return true;
  43128. }
  43129. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43130. };
  43131. /**
  43132. * Binds the given world matrix to the active effect
  43133. *
  43134. * @param world the matrix to bind
  43135. */
  43136. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43137. this._activeEffect.setMatrix("world", world);
  43138. };
  43139. /**
  43140. * Binds the given normal matrix to the active effect
  43141. *
  43142. * @param normalMatrix the matrix to bind
  43143. */
  43144. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43145. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43146. };
  43147. PushMaterial.prototype.bind = function (world, mesh) {
  43148. if (!mesh) {
  43149. return;
  43150. }
  43151. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43152. };
  43153. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43154. if (effect === void 0) { effect = null; }
  43155. _super.prototype._afterBind.call(this, mesh);
  43156. this.getScene()._cachedEffect = effect;
  43157. };
  43158. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43159. if (visibility === void 0) { visibility = 1; }
  43160. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43161. };
  43162. return PushMaterial;
  43163. }(BABYLON.Material));
  43164. BABYLON.PushMaterial = PushMaterial;
  43165. })(BABYLON || (BABYLON = {}));
  43166. //# sourceMappingURL=babylon.pushMaterial.js.map
  43167. var BABYLON;
  43168. (function (BABYLON) {
  43169. /** @hidden */
  43170. var StandardMaterialDefines = /** @class */ (function (_super) {
  43171. __extends(StandardMaterialDefines, _super);
  43172. function StandardMaterialDefines() {
  43173. var _this = _super.call(this) || this;
  43174. _this.MAINUV1 = false;
  43175. _this.MAINUV2 = false;
  43176. _this.DIFFUSE = false;
  43177. _this.DIFFUSEDIRECTUV = 0;
  43178. _this.AMBIENT = false;
  43179. _this.AMBIENTDIRECTUV = 0;
  43180. _this.OPACITY = false;
  43181. _this.OPACITYDIRECTUV = 0;
  43182. _this.OPACITYRGB = false;
  43183. _this.REFLECTION = false;
  43184. _this.EMISSIVE = false;
  43185. _this.EMISSIVEDIRECTUV = 0;
  43186. _this.SPECULAR = false;
  43187. _this.SPECULARDIRECTUV = 0;
  43188. _this.BUMP = false;
  43189. _this.BUMPDIRECTUV = 0;
  43190. _this.PARALLAX = false;
  43191. _this.PARALLAXOCCLUSION = false;
  43192. _this.SPECULAROVERALPHA = false;
  43193. _this.CLIPPLANE = false;
  43194. _this.ALPHATEST = false;
  43195. _this.DEPTHPREPASS = false;
  43196. _this.ALPHAFROMDIFFUSE = false;
  43197. _this.POINTSIZE = false;
  43198. _this.FOG = false;
  43199. _this.SPECULARTERM = false;
  43200. _this.DIFFUSEFRESNEL = false;
  43201. _this.OPACITYFRESNEL = false;
  43202. _this.REFLECTIONFRESNEL = false;
  43203. _this.REFRACTIONFRESNEL = false;
  43204. _this.EMISSIVEFRESNEL = false;
  43205. _this.FRESNEL = false;
  43206. _this.NORMAL = false;
  43207. _this.UV1 = false;
  43208. _this.UV2 = false;
  43209. _this.VERTEXCOLOR = false;
  43210. _this.VERTEXALPHA = false;
  43211. _this.NUM_BONE_INFLUENCERS = 0;
  43212. _this.BonesPerMesh = 0;
  43213. _this.INSTANCES = false;
  43214. _this.GLOSSINESS = false;
  43215. _this.ROUGHNESS = false;
  43216. _this.EMISSIVEASILLUMINATION = false;
  43217. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43218. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43219. _this.LIGHTMAP = false;
  43220. _this.LIGHTMAPDIRECTUV = 0;
  43221. _this.OBJECTSPACE_NORMALMAP = false;
  43222. _this.USELIGHTMAPASSHADOWMAP = false;
  43223. _this.REFLECTIONMAP_3D = false;
  43224. _this.REFLECTIONMAP_SPHERICAL = false;
  43225. _this.REFLECTIONMAP_PLANAR = false;
  43226. _this.REFLECTIONMAP_CUBIC = false;
  43227. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43228. _this.REFLECTIONMAP_PROJECTION = false;
  43229. _this.REFLECTIONMAP_SKYBOX = false;
  43230. _this.REFLECTIONMAP_EXPLICIT = false;
  43231. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43232. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43233. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43234. _this.INVERTCUBICMAP = false;
  43235. _this.LOGARITHMICDEPTH = false;
  43236. _this.REFRACTION = false;
  43237. _this.REFRACTIONMAP_3D = false;
  43238. _this.REFLECTIONOVERALPHA = false;
  43239. _this.TWOSIDEDLIGHTING = false;
  43240. _this.SHADOWFLOAT = false;
  43241. _this.MORPHTARGETS = false;
  43242. _this.MORPHTARGETS_NORMAL = false;
  43243. _this.MORPHTARGETS_TANGENT = false;
  43244. _this.NUM_MORPH_INFLUENCERS = 0;
  43245. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43246. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43247. _this.IMAGEPROCESSING = false;
  43248. _this.VIGNETTE = false;
  43249. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43250. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43251. _this.TONEMAPPING = false;
  43252. _this.CONTRAST = false;
  43253. _this.COLORCURVES = false;
  43254. _this.COLORGRADING = false;
  43255. _this.COLORGRADING3D = false;
  43256. _this.SAMPLER3DGREENDEPTH = false;
  43257. _this.SAMPLER3DBGRMAP = false;
  43258. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43259. /**
  43260. * If the reflection texture on this material is in linear color space
  43261. * @hidden
  43262. */
  43263. _this.IS_REFLECTION_LINEAR = false;
  43264. /**
  43265. * If the refraction texture on this material is in linear color space
  43266. * @hidden
  43267. */
  43268. _this.IS_REFRACTION_LINEAR = false;
  43269. _this.EXPOSURE = false;
  43270. _this.rebuild();
  43271. return _this;
  43272. }
  43273. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43274. var modes = [
  43275. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43276. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43277. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43278. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43279. ];
  43280. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43281. var mode = modes_1[_i];
  43282. this[mode] = (mode === modeToEnable);
  43283. }
  43284. };
  43285. return StandardMaterialDefines;
  43286. }(BABYLON.MaterialDefines));
  43287. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43288. var StandardMaterial = /** @class */ (function (_super) {
  43289. __extends(StandardMaterial, _super);
  43290. function StandardMaterial(name, scene) {
  43291. var _this = _super.call(this, name, scene) || this;
  43292. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43293. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43294. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43295. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43296. _this.specularPower = 64;
  43297. _this._useAlphaFromDiffuseTexture = false;
  43298. _this._useEmissiveAsIllumination = false;
  43299. _this._linkEmissiveWithDiffuse = false;
  43300. _this._useSpecularOverAlpha = false;
  43301. _this._useReflectionOverAlpha = false;
  43302. _this._disableLighting = false;
  43303. _this._useObjectSpaceNormalMap = false;
  43304. _this._useParallax = false;
  43305. _this._useParallaxOcclusion = false;
  43306. _this.parallaxScaleBias = 0.05;
  43307. _this._roughness = 0;
  43308. _this.indexOfRefraction = 0.98;
  43309. _this.invertRefractionY = true;
  43310. /**
  43311. * Defines the alpha limits in alpha test mode
  43312. */
  43313. _this.alphaCutOff = 0.4;
  43314. _this._useLightmapAsShadowmap = false;
  43315. _this._useReflectionFresnelFromSpecular = false;
  43316. _this._useGlossinessFromSpecularMapAlpha = false;
  43317. _this._maxSimultaneousLights = 4;
  43318. /**
  43319. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43320. */
  43321. _this._invertNormalMapX = false;
  43322. /**
  43323. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43324. */
  43325. _this._invertNormalMapY = false;
  43326. /**
  43327. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43328. */
  43329. _this._twoSidedLighting = false;
  43330. _this._renderTargets = new BABYLON.SmartArray(16);
  43331. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43332. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43333. // Setup the default processing configuration to the scene.
  43334. _this._attachImageProcessingConfiguration(null);
  43335. _this.getRenderTargetTextures = function () {
  43336. _this._renderTargets.reset();
  43337. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43338. _this._renderTargets.push(_this._reflectionTexture);
  43339. }
  43340. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43341. _this._renderTargets.push(_this._refractionTexture);
  43342. }
  43343. return _this._renderTargets;
  43344. };
  43345. return _this;
  43346. }
  43347. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43348. /**
  43349. * Gets the image processing configuration used either in this material.
  43350. */
  43351. get: function () {
  43352. return this._imageProcessingConfiguration;
  43353. },
  43354. /**
  43355. * Sets the Default image processing configuration used either in the this material.
  43356. *
  43357. * If sets to null, the scene one is in use.
  43358. */
  43359. set: function (value) {
  43360. this._attachImageProcessingConfiguration(value);
  43361. // Ensure the effect will be rebuilt.
  43362. this._markAllSubMeshesAsTexturesDirty();
  43363. },
  43364. enumerable: true,
  43365. configurable: true
  43366. });
  43367. /**
  43368. * Attaches a new image processing configuration to the Standard Material.
  43369. * @param configuration
  43370. */
  43371. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43372. var _this = this;
  43373. if (configuration === this._imageProcessingConfiguration) {
  43374. return;
  43375. }
  43376. // Detaches observer.
  43377. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43378. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43379. }
  43380. // Pick the scene configuration if needed.
  43381. if (!configuration) {
  43382. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43383. }
  43384. else {
  43385. this._imageProcessingConfiguration = configuration;
  43386. }
  43387. // Attaches observer.
  43388. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43389. _this._markAllSubMeshesAsImageProcessingDirty();
  43390. });
  43391. };
  43392. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43393. /**
  43394. * Gets wether the color curves effect is enabled.
  43395. */
  43396. get: function () {
  43397. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43398. },
  43399. /**
  43400. * Sets wether the color curves effect is enabled.
  43401. */
  43402. set: function (value) {
  43403. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43404. },
  43405. enumerable: true,
  43406. configurable: true
  43407. });
  43408. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43409. /**
  43410. * Gets wether the color grading effect is enabled.
  43411. */
  43412. get: function () {
  43413. return this.imageProcessingConfiguration.colorGradingEnabled;
  43414. },
  43415. /**
  43416. * Gets wether the color grading effect is enabled.
  43417. */
  43418. set: function (value) {
  43419. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43420. },
  43421. enumerable: true,
  43422. configurable: true
  43423. });
  43424. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43425. /**
  43426. * Gets wether tonemapping is enabled or not.
  43427. */
  43428. get: function () {
  43429. return this._imageProcessingConfiguration.toneMappingEnabled;
  43430. },
  43431. /**
  43432. * Sets wether tonemapping is enabled or not
  43433. */
  43434. set: function (value) {
  43435. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43436. },
  43437. enumerable: true,
  43438. configurable: true
  43439. });
  43440. ;
  43441. ;
  43442. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43443. /**
  43444. * The camera exposure used on this material.
  43445. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43446. * This corresponds to a photographic exposure.
  43447. */
  43448. get: function () {
  43449. return this._imageProcessingConfiguration.exposure;
  43450. },
  43451. /**
  43452. * The camera exposure used on this material.
  43453. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43454. * This corresponds to a photographic exposure.
  43455. */
  43456. set: function (value) {
  43457. this._imageProcessingConfiguration.exposure = value;
  43458. },
  43459. enumerable: true,
  43460. configurable: true
  43461. });
  43462. ;
  43463. ;
  43464. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43465. /**
  43466. * Gets The camera contrast used on this material.
  43467. */
  43468. get: function () {
  43469. return this._imageProcessingConfiguration.contrast;
  43470. },
  43471. /**
  43472. * Sets The camera contrast used on this material.
  43473. */
  43474. set: function (value) {
  43475. this._imageProcessingConfiguration.contrast = value;
  43476. },
  43477. enumerable: true,
  43478. configurable: true
  43479. });
  43480. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43481. /**
  43482. * Gets the Color Grading 2D Lookup Texture.
  43483. */
  43484. get: function () {
  43485. return this._imageProcessingConfiguration.colorGradingTexture;
  43486. },
  43487. /**
  43488. * Sets the Color Grading 2D Lookup Texture.
  43489. */
  43490. set: function (value) {
  43491. this._imageProcessingConfiguration.colorGradingTexture = value;
  43492. },
  43493. enumerable: true,
  43494. configurable: true
  43495. });
  43496. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43497. /**
  43498. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43499. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43500. * 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;
  43501. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43502. */
  43503. get: function () {
  43504. return this._imageProcessingConfiguration.colorCurves;
  43505. },
  43506. /**
  43507. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43508. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43509. * 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;
  43510. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43511. */
  43512. set: function (value) {
  43513. this._imageProcessingConfiguration.colorCurves = value;
  43514. },
  43515. enumerable: true,
  43516. configurable: true
  43517. });
  43518. StandardMaterial.prototype.getClassName = function () {
  43519. return "StandardMaterial";
  43520. };
  43521. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43522. get: function () {
  43523. return this._useLogarithmicDepth;
  43524. },
  43525. set: function (value) {
  43526. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43527. this._markAllSubMeshesAsMiscDirty();
  43528. },
  43529. enumerable: true,
  43530. configurable: true
  43531. });
  43532. StandardMaterial.prototype.needAlphaBlending = function () {
  43533. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43534. };
  43535. StandardMaterial.prototype.needAlphaTesting = function () {
  43536. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43537. };
  43538. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43539. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43540. };
  43541. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43542. return this._diffuseTexture;
  43543. };
  43544. /**
  43545. * Child classes can use it to update shaders
  43546. */
  43547. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43548. if (useInstances === void 0) { useInstances = false; }
  43549. if (subMesh.effect && this.isFrozen) {
  43550. if (this._wasPreviouslyReady && subMesh.effect) {
  43551. return true;
  43552. }
  43553. }
  43554. if (!subMesh._materialDefines) {
  43555. subMesh._materialDefines = new StandardMaterialDefines();
  43556. }
  43557. var scene = this.getScene();
  43558. var defines = subMesh._materialDefines;
  43559. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43560. if (defines._renderId === scene.getRenderId()) {
  43561. return true;
  43562. }
  43563. }
  43564. var engine = scene.getEngine();
  43565. // Lights
  43566. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43567. // Textures
  43568. if (defines._areTexturesDirty) {
  43569. defines._needUVs = false;
  43570. defines.MAINUV1 = false;
  43571. defines.MAINUV2 = false;
  43572. if (scene.texturesEnabled) {
  43573. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43574. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43575. return false;
  43576. }
  43577. else {
  43578. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43579. }
  43580. }
  43581. else {
  43582. defines.DIFFUSE = false;
  43583. }
  43584. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43585. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43586. return false;
  43587. }
  43588. else {
  43589. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43590. }
  43591. }
  43592. else {
  43593. defines.AMBIENT = false;
  43594. }
  43595. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43596. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43597. return false;
  43598. }
  43599. else {
  43600. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43601. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43602. }
  43603. }
  43604. else {
  43605. defines.OPACITY = false;
  43606. }
  43607. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43608. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43609. return false;
  43610. }
  43611. else {
  43612. defines._needNormals = true;
  43613. defines.REFLECTION = true;
  43614. defines.ROUGHNESS = (this._roughness > 0);
  43615. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43616. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43617. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43618. switch (this._reflectionTexture.coordinatesMode) {
  43619. case BABYLON.Texture.EXPLICIT_MODE:
  43620. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43621. break;
  43622. case BABYLON.Texture.PLANAR_MODE:
  43623. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43624. break;
  43625. case BABYLON.Texture.PROJECTION_MODE:
  43626. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43627. break;
  43628. case BABYLON.Texture.SKYBOX_MODE:
  43629. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43630. break;
  43631. case BABYLON.Texture.SPHERICAL_MODE:
  43632. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43633. break;
  43634. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43635. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43636. break;
  43637. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43638. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43639. break;
  43640. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43641. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43642. break;
  43643. case BABYLON.Texture.CUBIC_MODE:
  43644. case BABYLON.Texture.INVCUBIC_MODE:
  43645. default:
  43646. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43647. break;
  43648. }
  43649. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43650. }
  43651. }
  43652. else {
  43653. defines.REFLECTION = false;
  43654. }
  43655. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43656. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43657. return false;
  43658. }
  43659. else {
  43660. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43661. }
  43662. }
  43663. else {
  43664. defines.EMISSIVE = false;
  43665. }
  43666. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43667. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43668. return false;
  43669. }
  43670. else {
  43671. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43672. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43673. }
  43674. }
  43675. else {
  43676. defines.LIGHTMAP = false;
  43677. }
  43678. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43679. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43680. return false;
  43681. }
  43682. else {
  43683. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43684. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43685. }
  43686. }
  43687. else {
  43688. defines.SPECULAR = false;
  43689. }
  43690. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43691. // Bump texure can not be not blocking.
  43692. if (!this._bumpTexture.isReady()) {
  43693. return false;
  43694. }
  43695. else {
  43696. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43697. defines.PARALLAX = this._useParallax;
  43698. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43699. }
  43700. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43701. }
  43702. else {
  43703. defines.BUMP = false;
  43704. }
  43705. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43706. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43707. return false;
  43708. }
  43709. else {
  43710. defines._needUVs = true;
  43711. defines.REFRACTION = true;
  43712. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43713. }
  43714. }
  43715. else {
  43716. defines.REFRACTION = false;
  43717. }
  43718. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43719. }
  43720. else {
  43721. defines.DIFFUSE = false;
  43722. defines.AMBIENT = false;
  43723. defines.OPACITY = false;
  43724. defines.REFLECTION = false;
  43725. defines.EMISSIVE = false;
  43726. defines.LIGHTMAP = false;
  43727. defines.BUMP = false;
  43728. defines.REFRACTION = false;
  43729. }
  43730. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43731. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43732. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43733. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43734. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43735. }
  43736. if (defines._areImageProcessingDirty) {
  43737. if (!this._imageProcessingConfiguration.isReady()) {
  43738. return false;
  43739. }
  43740. this._imageProcessingConfiguration.prepareDefines(defines);
  43741. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43742. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43743. }
  43744. if (defines._areFresnelDirty) {
  43745. if (StandardMaterial.FresnelEnabled) {
  43746. // Fresnel
  43747. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43748. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43749. this._reflectionFresnelParameters) {
  43750. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43751. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43752. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43753. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43754. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43755. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43756. defines._needNormals = true;
  43757. defines.FRESNEL = true;
  43758. }
  43759. }
  43760. else {
  43761. defines.FRESNEL = false;
  43762. }
  43763. }
  43764. // Misc.
  43765. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43766. // Attribs
  43767. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43768. // Values that need to be evaluated on every frame
  43769. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43770. // Get correct effect
  43771. if (defines.isDirty) {
  43772. defines.markAsProcessed();
  43773. scene.resetCachedMaterial();
  43774. // Fallbacks
  43775. var fallbacks = new BABYLON.EffectFallbacks();
  43776. if (defines.REFLECTION) {
  43777. fallbacks.addFallback(0, "REFLECTION");
  43778. }
  43779. if (defines.SPECULAR) {
  43780. fallbacks.addFallback(0, "SPECULAR");
  43781. }
  43782. if (defines.BUMP) {
  43783. fallbacks.addFallback(0, "BUMP");
  43784. }
  43785. if (defines.PARALLAX) {
  43786. fallbacks.addFallback(1, "PARALLAX");
  43787. }
  43788. if (defines.PARALLAXOCCLUSION) {
  43789. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43790. }
  43791. if (defines.SPECULAROVERALPHA) {
  43792. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43793. }
  43794. if (defines.FOG) {
  43795. fallbacks.addFallback(1, "FOG");
  43796. }
  43797. if (defines.POINTSIZE) {
  43798. fallbacks.addFallback(0, "POINTSIZE");
  43799. }
  43800. if (defines.LOGARITHMICDEPTH) {
  43801. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43802. }
  43803. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43804. if (defines.SPECULARTERM) {
  43805. fallbacks.addFallback(0, "SPECULARTERM");
  43806. }
  43807. if (defines.DIFFUSEFRESNEL) {
  43808. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43809. }
  43810. if (defines.OPACITYFRESNEL) {
  43811. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43812. }
  43813. if (defines.REFLECTIONFRESNEL) {
  43814. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43815. }
  43816. if (defines.EMISSIVEFRESNEL) {
  43817. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43818. }
  43819. if (defines.FRESNEL) {
  43820. fallbacks.addFallback(4, "FRESNEL");
  43821. }
  43822. //Attributes
  43823. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43824. if (defines.NORMAL) {
  43825. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43826. }
  43827. if (defines.UV1) {
  43828. attribs.push(BABYLON.VertexBuffer.UVKind);
  43829. }
  43830. if (defines.UV2) {
  43831. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43832. }
  43833. if (defines.VERTEXCOLOR) {
  43834. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43835. }
  43836. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43837. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43838. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43839. var shaderName = "default";
  43840. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43841. "vFogInfos", "vFogColor", "pointSize",
  43842. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43843. "mBones",
  43844. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43845. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43846. "vReflectionPosition", "vReflectionSize",
  43847. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43848. ];
  43849. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43850. var uniformBuffers = ["Material", "Scene"];
  43851. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43852. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43853. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43854. uniformsNames: uniforms,
  43855. uniformBuffersNames: uniformBuffers,
  43856. samplers: samplers,
  43857. defines: defines,
  43858. maxSimultaneousLights: this._maxSimultaneousLights
  43859. });
  43860. if (this.customShaderNameResolve) {
  43861. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43862. }
  43863. var join = defines.toString();
  43864. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43865. attributes: attribs,
  43866. uniformsNames: uniforms,
  43867. uniformBuffersNames: uniformBuffers,
  43868. samplers: samplers,
  43869. defines: join,
  43870. fallbacks: fallbacks,
  43871. onCompiled: this.onCompiled,
  43872. onError: this.onError,
  43873. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43874. }, engine), defines);
  43875. this.buildUniformLayout();
  43876. }
  43877. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43878. return false;
  43879. }
  43880. defines._renderId = scene.getRenderId();
  43881. this._wasPreviouslyReady = true;
  43882. return true;
  43883. };
  43884. StandardMaterial.prototype.buildUniformLayout = function () {
  43885. // Order is important !
  43886. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43887. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43888. this._uniformBuffer.addUniform("opacityParts", 4);
  43889. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43890. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43891. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43892. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43893. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43894. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43895. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43896. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43897. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43898. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43899. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43900. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43901. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43902. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43903. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43904. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43905. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43906. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43907. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43908. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43909. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43910. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43911. this._uniformBuffer.addUniform("specularMatrix", 16);
  43912. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43913. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43914. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43915. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43916. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43917. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43918. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43919. this._uniformBuffer.addUniform("pointSize", 1);
  43920. this._uniformBuffer.create();
  43921. };
  43922. StandardMaterial.prototype.unbind = function () {
  43923. if (this._activeEffect) {
  43924. var needFlag = false;
  43925. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43926. this._activeEffect.setTexture("reflection2DSampler", null);
  43927. needFlag = true;
  43928. }
  43929. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43930. this._activeEffect.setTexture("refraction2DSampler", null);
  43931. needFlag = true;
  43932. }
  43933. if (needFlag) {
  43934. this._markAllSubMeshesAsTexturesDirty();
  43935. }
  43936. }
  43937. _super.prototype.unbind.call(this);
  43938. };
  43939. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43940. var scene = this.getScene();
  43941. var defines = subMesh._materialDefines;
  43942. if (!defines) {
  43943. return;
  43944. }
  43945. var effect = subMesh.effect;
  43946. if (!effect) {
  43947. return;
  43948. }
  43949. this._activeEffect = effect;
  43950. // Matrices
  43951. this.bindOnlyWorldMatrix(world);
  43952. // Normal Matrix
  43953. if (defines.OBJECTSPACE_NORMALMAP) {
  43954. world.toNormalMatrix(this._normalMatrix);
  43955. this.bindOnlyNormalMatrix(this._normalMatrix);
  43956. }
  43957. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43958. // Bones
  43959. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43960. if (mustRebind) {
  43961. this._uniformBuffer.bindToEffect(effect, "Material");
  43962. this.bindViewProjection(effect);
  43963. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43964. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43965. // Fresnel
  43966. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43967. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43968. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43969. }
  43970. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43971. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43972. }
  43973. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43974. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43975. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43976. }
  43977. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43978. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43979. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43980. }
  43981. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43982. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43983. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43984. }
  43985. }
  43986. // Textures
  43987. if (scene.texturesEnabled) {
  43988. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43989. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43990. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43991. if (this._diffuseTexture.hasAlpha) {
  43992. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43993. }
  43994. }
  43995. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43996. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43997. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43998. }
  43999. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44000. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44001. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44002. }
  44003. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44004. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44005. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44006. if (this._reflectionTexture.boundingBoxSize) {
  44007. var cubeTexture = this._reflectionTexture;
  44008. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44009. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44010. }
  44011. }
  44012. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44013. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44014. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44015. }
  44016. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44017. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44018. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44019. }
  44020. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44021. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44022. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44023. }
  44024. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44025. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44026. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44027. if (scene._mirroredCameraPosition) {
  44028. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44029. }
  44030. else {
  44031. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44032. }
  44033. }
  44034. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44035. var depth = 1.0;
  44036. if (!this._refractionTexture.isCube) {
  44037. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44038. if (this._refractionTexture.depth) {
  44039. depth = this._refractionTexture.depth;
  44040. }
  44041. }
  44042. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44043. }
  44044. }
  44045. // Point size
  44046. if (this.pointsCloud) {
  44047. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44048. }
  44049. if (defines.SPECULARTERM) {
  44050. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44051. }
  44052. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44053. // Diffuse
  44054. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44055. }
  44056. // Textures
  44057. if (scene.texturesEnabled) {
  44058. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44059. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44060. }
  44061. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44062. effect.setTexture("ambientSampler", this._ambientTexture);
  44063. }
  44064. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44065. effect.setTexture("opacitySampler", this._opacityTexture);
  44066. }
  44067. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44068. if (this._reflectionTexture.isCube) {
  44069. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44070. }
  44071. else {
  44072. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44073. }
  44074. }
  44075. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44076. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44077. }
  44078. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44079. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44080. }
  44081. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44082. effect.setTexture("specularSampler", this._specularTexture);
  44083. }
  44084. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44085. effect.setTexture("bumpSampler", this._bumpTexture);
  44086. }
  44087. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44088. var depth = 1.0;
  44089. if (this._refractionTexture.isCube) {
  44090. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44091. }
  44092. else {
  44093. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44094. }
  44095. }
  44096. }
  44097. // Clip plane
  44098. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44099. // Colors
  44100. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44101. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44102. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44103. }
  44104. if (mustRebind || !this.isFrozen) {
  44105. // Lights
  44106. if (scene.lightsEnabled && !this._disableLighting) {
  44107. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44108. }
  44109. // View
  44110. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44111. this.bindView(effect);
  44112. }
  44113. // Fog
  44114. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44115. // Morph targets
  44116. if (defines.NUM_MORPH_INFLUENCERS) {
  44117. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44118. }
  44119. // Log. depth
  44120. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44121. // image processing
  44122. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44123. this._imageProcessingConfiguration.bind(this._activeEffect);
  44124. }
  44125. }
  44126. this._uniformBuffer.update();
  44127. this._afterBind(mesh, this._activeEffect);
  44128. };
  44129. StandardMaterial.prototype.getAnimatables = function () {
  44130. var results = [];
  44131. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44132. results.push(this._diffuseTexture);
  44133. }
  44134. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44135. results.push(this._ambientTexture);
  44136. }
  44137. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44138. results.push(this._opacityTexture);
  44139. }
  44140. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44141. results.push(this._reflectionTexture);
  44142. }
  44143. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44144. results.push(this._emissiveTexture);
  44145. }
  44146. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44147. results.push(this._specularTexture);
  44148. }
  44149. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44150. results.push(this._bumpTexture);
  44151. }
  44152. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44153. results.push(this._lightmapTexture);
  44154. }
  44155. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44156. results.push(this._refractionTexture);
  44157. }
  44158. return results;
  44159. };
  44160. StandardMaterial.prototype.getActiveTextures = function () {
  44161. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44162. if (this._diffuseTexture) {
  44163. activeTextures.push(this._diffuseTexture);
  44164. }
  44165. if (this._ambientTexture) {
  44166. activeTextures.push(this._ambientTexture);
  44167. }
  44168. if (this._opacityTexture) {
  44169. activeTextures.push(this._opacityTexture);
  44170. }
  44171. if (this._reflectionTexture) {
  44172. activeTextures.push(this._reflectionTexture);
  44173. }
  44174. if (this._emissiveTexture) {
  44175. activeTextures.push(this._emissiveTexture);
  44176. }
  44177. if (this._specularTexture) {
  44178. activeTextures.push(this._specularTexture);
  44179. }
  44180. if (this._bumpTexture) {
  44181. activeTextures.push(this._bumpTexture);
  44182. }
  44183. if (this._lightmapTexture) {
  44184. activeTextures.push(this._lightmapTexture);
  44185. }
  44186. if (this._refractionTexture) {
  44187. activeTextures.push(this._refractionTexture);
  44188. }
  44189. return activeTextures;
  44190. };
  44191. StandardMaterial.prototype.hasTexture = function (texture) {
  44192. if (_super.prototype.hasTexture.call(this, texture)) {
  44193. return true;
  44194. }
  44195. if (this._diffuseTexture === texture) {
  44196. return true;
  44197. }
  44198. if (this._ambientTexture === texture) {
  44199. return true;
  44200. }
  44201. if (this._opacityTexture === texture) {
  44202. return true;
  44203. }
  44204. if (this._reflectionTexture === texture) {
  44205. return true;
  44206. }
  44207. if (this._emissiveTexture === texture) {
  44208. return true;
  44209. }
  44210. if (this._specularTexture === texture) {
  44211. return true;
  44212. }
  44213. if (this._bumpTexture === texture) {
  44214. return true;
  44215. }
  44216. if (this._lightmapTexture === texture) {
  44217. return true;
  44218. }
  44219. if (this._refractionTexture === texture) {
  44220. return true;
  44221. }
  44222. return false;
  44223. };
  44224. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44225. if (forceDisposeTextures) {
  44226. if (this._diffuseTexture) {
  44227. this._diffuseTexture.dispose();
  44228. }
  44229. if (this._ambientTexture) {
  44230. this._ambientTexture.dispose();
  44231. }
  44232. if (this._opacityTexture) {
  44233. this._opacityTexture.dispose();
  44234. }
  44235. if (this._reflectionTexture) {
  44236. this._reflectionTexture.dispose();
  44237. }
  44238. if (this._emissiveTexture) {
  44239. this._emissiveTexture.dispose();
  44240. }
  44241. if (this._specularTexture) {
  44242. this._specularTexture.dispose();
  44243. }
  44244. if (this._bumpTexture) {
  44245. this._bumpTexture.dispose();
  44246. }
  44247. if (this._lightmapTexture) {
  44248. this._lightmapTexture.dispose();
  44249. }
  44250. if (this._refractionTexture) {
  44251. this._refractionTexture.dispose();
  44252. }
  44253. }
  44254. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44255. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44256. }
  44257. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44258. };
  44259. StandardMaterial.prototype.clone = function (name) {
  44260. var _this = this;
  44261. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44262. result.name = name;
  44263. result.id = name;
  44264. return result;
  44265. };
  44266. StandardMaterial.prototype.serialize = function () {
  44267. return BABYLON.SerializationHelper.Serialize(this);
  44268. };
  44269. // Statics
  44270. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44271. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44272. };
  44273. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44274. get: function () {
  44275. return StandardMaterial._DiffuseTextureEnabled;
  44276. },
  44277. set: function (value) {
  44278. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44279. return;
  44280. }
  44281. StandardMaterial._DiffuseTextureEnabled = value;
  44282. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44283. },
  44284. enumerable: true,
  44285. configurable: true
  44286. });
  44287. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44288. get: function () {
  44289. return StandardMaterial._AmbientTextureEnabled;
  44290. },
  44291. set: function (value) {
  44292. if (StandardMaterial._AmbientTextureEnabled === value) {
  44293. return;
  44294. }
  44295. StandardMaterial._AmbientTextureEnabled = value;
  44296. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44297. },
  44298. enumerable: true,
  44299. configurable: true
  44300. });
  44301. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44302. get: function () {
  44303. return StandardMaterial._OpacityTextureEnabled;
  44304. },
  44305. set: function (value) {
  44306. if (StandardMaterial._OpacityTextureEnabled === value) {
  44307. return;
  44308. }
  44309. StandardMaterial._OpacityTextureEnabled = value;
  44310. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44311. },
  44312. enumerable: true,
  44313. configurable: true
  44314. });
  44315. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44316. get: function () {
  44317. return StandardMaterial._ReflectionTextureEnabled;
  44318. },
  44319. set: function (value) {
  44320. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44321. return;
  44322. }
  44323. StandardMaterial._ReflectionTextureEnabled = value;
  44324. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44325. },
  44326. enumerable: true,
  44327. configurable: true
  44328. });
  44329. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44330. get: function () {
  44331. return StandardMaterial._EmissiveTextureEnabled;
  44332. },
  44333. set: function (value) {
  44334. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44335. return;
  44336. }
  44337. StandardMaterial._EmissiveTextureEnabled = value;
  44338. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44339. },
  44340. enumerable: true,
  44341. configurable: true
  44342. });
  44343. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44344. get: function () {
  44345. return StandardMaterial._SpecularTextureEnabled;
  44346. },
  44347. set: function (value) {
  44348. if (StandardMaterial._SpecularTextureEnabled === value) {
  44349. return;
  44350. }
  44351. StandardMaterial._SpecularTextureEnabled = value;
  44352. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44353. },
  44354. enumerable: true,
  44355. configurable: true
  44356. });
  44357. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44358. get: function () {
  44359. return StandardMaterial._BumpTextureEnabled;
  44360. },
  44361. set: function (value) {
  44362. if (StandardMaterial._BumpTextureEnabled === value) {
  44363. return;
  44364. }
  44365. StandardMaterial._BumpTextureEnabled = value;
  44366. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44367. },
  44368. enumerable: true,
  44369. configurable: true
  44370. });
  44371. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44372. get: function () {
  44373. return StandardMaterial._LightmapTextureEnabled;
  44374. },
  44375. set: function (value) {
  44376. if (StandardMaterial._LightmapTextureEnabled === value) {
  44377. return;
  44378. }
  44379. StandardMaterial._LightmapTextureEnabled = value;
  44380. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44381. },
  44382. enumerable: true,
  44383. configurable: true
  44384. });
  44385. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44386. get: function () {
  44387. return StandardMaterial._RefractionTextureEnabled;
  44388. },
  44389. set: function (value) {
  44390. if (StandardMaterial._RefractionTextureEnabled === value) {
  44391. return;
  44392. }
  44393. StandardMaterial._RefractionTextureEnabled = value;
  44394. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44395. },
  44396. enumerable: true,
  44397. configurable: true
  44398. });
  44399. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44400. get: function () {
  44401. return StandardMaterial._ColorGradingTextureEnabled;
  44402. },
  44403. set: function (value) {
  44404. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44405. return;
  44406. }
  44407. StandardMaterial._ColorGradingTextureEnabled = value;
  44408. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44409. },
  44410. enumerable: true,
  44411. configurable: true
  44412. });
  44413. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44414. get: function () {
  44415. return StandardMaterial._FresnelEnabled;
  44416. },
  44417. set: function (value) {
  44418. if (StandardMaterial._FresnelEnabled === value) {
  44419. return;
  44420. }
  44421. StandardMaterial._FresnelEnabled = value;
  44422. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44423. },
  44424. enumerable: true,
  44425. configurable: true
  44426. });
  44427. // Flags used to enable or disable a type of texture for all Standard Materials
  44428. StandardMaterial._DiffuseTextureEnabled = true;
  44429. StandardMaterial._AmbientTextureEnabled = true;
  44430. StandardMaterial._OpacityTextureEnabled = true;
  44431. StandardMaterial._ReflectionTextureEnabled = true;
  44432. StandardMaterial._EmissiveTextureEnabled = true;
  44433. StandardMaterial._SpecularTextureEnabled = true;
  44434. StandardMaterial._BumpTextureEnabled = true;
  44435. StandardMaterial._LightmapTextureEnabled = true;
  44436. StandardMaterial._RefractionTextureEnabled = true;
  44437. StandardMaterial._ColorGradingTextureEnabled = true;
  44438. StandardMaterial._FresnelEnabled = true;
  44439. __decorate([
  44440. BABYLON.serializeAsTexture("diffuseTexture")
  44441. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44442. __decorate([
  44443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44444. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44445. __decorate([
  44446. BABYLON.serializeAsTexture("ambientTexture")
  44447. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44448. __decorate([
  44449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44450. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44451. __decorate([
  44452. BABYLON.serializeAsTexture("opacityTexture")
  44453. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44454. __decorate([
  44455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44456. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44457. __decorate([
  44458. BABYLON.serializeAsTexture("reflectionTexture")
  44459. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44460. __decorate([
  44461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44462. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44463. __decorate([
  44464. BABYLON.serializeAsTexture("emissiveTexture")
  44465. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44466. __decorate([
  44467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44468. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44469. __decorate([
  44470. BABYLON.serializeAsTexture("specularTexture")
  44471. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44472. __decorate([
  44473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44474. ], StandardMaterial.prototype, "specularTexture", void 0);
  44475. __decorate([
  44476. BABYLON.serializeAsTexture("bumpTexture")
  44477. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44478. __decorate([
  44479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44480. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44481. __decorate([
  44482. BABYLON.serializeAsTexture("lightmapTexture")
  44483. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44484. __decorate([
  44485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44486. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44487. __decorate([
  44488. BABYLON.serializeAsTexture("refractionTexture")
  44489. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44490. __decorate([
  44491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44492. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44493. __decorate([
  44494. BABYLON.serializeAsColor3("ambient")
  44495. ], StandardMaterial.prototype, "ambientColor", void 0);
  44496. __decorate([
  44497. BABYLON.serializeAsColor3("diffuse")
  44498. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44499. __decorate([
  44500. BABYLON.serializeAsColor3("specular")
  44501. ], StandardMaterial.prototype, "specularColor", void 0);
  44502. __decorate([
  44503. BABYLON.serializeAsColor3("emissive")
  44504. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44505. __decorate([
  44506. BABYLON.serialize()
  44507. ], StandardMaterial.prototype, "specularPower", void 0);
  44508. __decorate([
  44509. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44510. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44511. __decorate([
  44512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44513. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44514. __decorate([
  44515. BABYLON.serialize("useEmissiveAsIllumination")
  44516. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44517. __decorate([
  44518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44519. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44520. __decorate([
  44521. BABYLON.serialize("linkEmissiveWithDiffuse")
  44522. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44523. __decorate([
  44524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44525. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44526. __decorate([
  44527. BABYLON.serialize("useSpecularOverAlpha")
  44528. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44529. __decorate([
  44530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44531. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44532. __decorate([
  44533. BABYLON.serialize("useReflectionOverAlpha")
  44534. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44535. __decorate([
  44536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44537. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44538. __decorate([
  44539. BABYLON.serialize("disableLighting")
  44540. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44541. __decorate([
  44542. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44543. ], StandardMaterial.prototype, "disableLighting", void 0);
  44544. __decorate([
  44545. BABYLON.serialize("useObjectSpaceNormalMap")
  44546. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44547. __decorate([
  44548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44549. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44550. __decorate([
  44551. BABYLON.serialize("useParallax")
  44552. ], StandardMaterial.prototype, "_useParallax", void 0);
  44553. __decorate([
  44554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44555. ], StandardMaterial.prototype, "useParallax", void 0);
  44556. __decorate([
  44557. BABYLON.serialize("useParallaxOcclusion")
  44558. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44559. __decorate([
  44560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44561. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44562. __decorate([
  44563. BABYLON.serialize()
  44564. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44565. __decorate([
  44566. BABYLON.serialize("roughness")
  44567. ], StandardMaterial.prototype, "_roughness", void 0);
  44568. __decorate([
  44569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44570. ], StandardMaterial.prototype, "roughness", void 0);
  44571. __decorate([
  44572. BABYLON.serialize()
  44573. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44574. __decorate([
  44575. BABYLON.serialize()
  44576. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44577. __decorate([
  44578. BABYLON.serialize()
  44579. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44580. __decorate([
  44581. BABYLON.serialize("useLightmapAsShadowmap")
  44582. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44583. __decorate([
  44584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44585. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44586. __decorate([
  44587. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44588. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44589. __decorate([
  44590. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44591. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44592. __decorate([
  44593. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44594. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44595. __decorate([
  44596. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44597. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44598. __decorate([
  44599. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44600. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44601. __decorate([
  44602. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44603. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44604. __decorate([
  44605. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44606. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44607. __decorate([
  44608. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44609. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44610. __decorate([
  44611. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44612. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44613. __decorate([
  44614. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44615. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44616. __decorate([
  44617. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44618. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44619. __decorate([
  44620. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44621. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44622. __decorate([
  44623. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44624. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44625. __decorate([
  44626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44627. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44628. __decorate([
  44629. BABYLON.serialize("maxSimultaneousLights")
  44630. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44631. __decorate([
  44632. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44633. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44634. __decorate([
  44635. BABYLON.serialize("invertNormalMapX")
  44636. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44637. __decorate([
  44638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44639. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44640. __decorate([
  44641. BABYLON.serialize("invertNormalMapY")
  44642. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44643. __decorate([
  44644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44645. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44646. __decorate([
  44647. BABYLON.serialize("twoSidedLighting")
  44648. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44649. __decorate([
  44650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44651. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44652. __decorate([
  44653. BABYLON.serialize()
  44654. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44655. return StandardMaterial;
  44656. }(BABYLON.PushMaterial));
  44657. BABYLON.StandardMaterial = StandardMaterial;
  44658. })(BABYLON || (BABYLON = {}));
  44659. //# sourceMappingURL=babylon.standardMaterial.js.map
  44660. var BABYLON;
  44661. (function (BABYLON) {
  44662. /**
  44663. * Manages the defines for the PBR Material.
  44664. * @hiddenChildren
  44665. */
  44666. var PBRMaterialDefines = /** @class */ (function (_super) {
  44667. __extends(PBRMaterialDefines, _super);
  44668. /**
  44669. * Initializes the PBR Material defines.
  44670. */
  44671. function PBRMaterialDefines() {
  44672. var _this = _super.call(this) || this;
  44673. _this.PBR = true;
  44674. _this.MAINUV1 = false;
  44675. _this.MAINUV2 = false;
  44676. _this.UV1 = false;
  44677. _this.UV2 = false;
  44678. _this.ALBEDO = false;
  44679. _this.ALBEDODIRECTUV = 0;
  44680. _this.VERTEXCOLOR = false;
  44681. _this.AMBIENT = false;
  44682. _this.AMBIENTDIRECTUV = 0;
  44683. _this.AMBIENTINGRAYSCALE = false;
  44684. _this.OPACITY = false;
  44685. _this.VERTEXALPHA = false;
  44686. _this.OPACITYDIRECTUV = 0;
  44687. _this.OPACITYRGB = false;
  44688. _this.ALPHATEST = false;
  44689. _this.DEPTHPREPASS = false;
  44690. _this.ALPHABLEND = false;
  44691. _this.ALPHAFROMALBEDO = false;
  44692. _this.ALPHATESTVALUE = "0.5";
  44693. _this.SPECULAROVERALPHA = false;
  44694. _this.RADIANCEOVERALPHA = false;
  44695. _this.ALPHAFRESNEL = false;
  44696. _this.LINEARALPHAFRESNEL = false;
  44697. _this.PREMULTIPLYALPHA = false;
  44698. _this.EMISSIVE = false;
  44699. _this.EMISSIVEDIRECTUV = 0;
  44700. _this.REFLECTIVITY = false;
  44701. _this.REFLECTIVITYDIRECTUV = 0;
  44702. _this.SPECULARTERM = false;
  44703. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44704. _this.MICROSURFACEAUTOMATIC = false;
  44705. _this.LODBASEDMICROSFURACE = false;
  44706. _this.MICROSURFACEMAP = false;
  44707. _this.MICROSURFACEMAPDIRECTUV = 0;
  44708. _this.METALLICWORKFLOW = false;
  44709. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44710. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44711. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44712. _this.AOSTOREINMETALMAPRED = false;
  44713. _this.ENVIRONMENTBRDF = false;
  44714. _this.NORMAL = false;
  44715. _this.TANGENT = false;
  44716. _this.BUMP = false;
  44717. _this.BUMPDIRECTUV = 0;
  44718. _this.OBJECTSPACE_NORMALMAP = false;
  44719. _this.PARALLAX = false;
  44720. _this.PARALLAXOCCLUSION = false;
  44721. _this.NORMALXYSCALE = true;
  44722. _this.LIGHTMAP = false;
  44723. _this.LIGHTMAPDIRECTUV = 0;
  44724. _this.USELIGHTMAPASSHADOWMAP = false;
  44725. _this.GAMMALIGHTMAP = false;
  44726. _this.REFLECTION = false;
  44727. _this.REFLECTIONMAP_3D = false;
  44728. _this.REFLECTIONMAP_SPHERICAL = false;
  44729. _this.REFLECTIONMAP_PLANAR = false;
  44730. _this.REFLECTIONMAP_CUBIC = false;
  44731. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44732. _this.REFLECTIONMAP_PROJECTION = false;
  44733. _this.REFLECTIONMAP_SKYBOX = false;
  44734. _this.REFLECTIONMAP_EXPLICIT = false;
  44735. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44736. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44737. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44738. _this.INVERTCUBICMAP = false;
  44739. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44740. _this.USESPHERICALINVERTEX = false;
  44741. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44742. _this.LODINREFLECTIONALPHA = false;
  44743. _this.GAMMAREFLECTION = false;
  44744. _this.RGBDREFLECTION = false;
  44745. _this.RADIANCEOCCLUSION = false;
  44746. _this.HORIZONOCCLUSION = false;
  44747. _this.REFRACTION = false;
  44748. _this.REFRACTIONMAP_3D = false;
  44749. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44750. _this.LODINREFRACTIONALPHA = false;
  44751. _this.GAMMAREFRACTION = false;
  44752. _this.RGBDREFRACTION = false;
  44753. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44754. _this.INSTANCES = false;
  44755. _this.NUM_BONE_INFLUENCERS = 0;
  44756. _this.BonesPerMesh = 0;
  44757. _this.NONUNIFORMSCALING = false;
  44758. _this.MORPHTARGETS = false;
  44759. _this.MORPHTARGETS_NORMAL = false;
  44760. _this.MORPHTARGETS_TANGENT = false;
  44761. _this.NUM_MORPH_INFLUENCERS = 0;
  44762. _this.IMAGEPROCESSING = false;
  44763. _this.VIGNETTE = false;
  44764. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44765. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44766. _this.TONEMAPPING = false;
  44767. _this.CONTRAST = false;
  44768. _this.COLORCURVES = false;
  44769. _this.COLORGRADING = false;
  44770. _this.COLORGRADING3D = false;
  44771. _this.SAMPLER3DGREENDEPTH = false;
  44772. _this.SAMPLER3DBGRMAP = false;
  44773. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44774. _this.EXPOSURE = false;
  44775. _this.USEPHYSICALLIGHTFALLOFF = false;
  44776. _this.TWOSIDEDLIGHTING = false;
  44777. _this.SHADOWFLOAT = false;
  44778. _this.CLIPPLANE = false;
  44779. _this.POINTSIZE = false;
  44780. _this.FOG = false;
  44781. _this.LOGARITHMICDEPTH = false;
  44782. _this.FORCENORMALFORWARD = false;
  44783. _this.SPECULARAA = false;
  44784. _this.UNLIT = false;
  44785. _this.rebuild();
  44786. return _this;
  44787. }
  44788. /**
  44789. * Resets the PBR Material defines.
  44790. */
  44791. PBRMaterialDefines.prototype.reset = function () {
  44792. _super.prototype.reset.call(this);
  44793. this.ALPHATESTVALUE = "0.5";
  44794. this.PBR = true;
  44795. };
  44796. return PBRMaterialDefines;
  44797. }(BABYLON.MaterialDefines));
  44798. /**
  44799. * The Physically based material base class of BJS.
  44800. *
  44801. * This offers the main features of a standard PBR material.
  44802. * For more information, please refer to the documentation :
  44803. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44804. */
  44805. var PBRBaseMaterial = /** @class */ (function (_super) {
  44806. __extends(PBRBaseMaterial, _super);
  44807. /**
  44808. * Instantiates a new PBRMaterial instance.
  44809. *
  44810. * @param name The material name
  44811. * @param scene The scene the material will be use in.
  44812. */
  44813. function PBRBaseMaterial(name, scene) {
  44814. var _this = _super.call(this, name, scene) || this;
  44815. /**
  44816. * Intensity of the direct lights e.g. the four lights available in your scene.
  44817. * This impacts both the direct diffuse and specular highlights.
  44818. */
  44819. _this._directIntensity = 1.0;
  44820. /**
  44821. * Intensity of the emissive part of the material.
  44822. * This helps controlling the emissive effect without modifying the emissive color.
  44823. */
  44824. _this._emissiveIntensity = 1.0;
  44825. /**
  44826. * Intensity of the environment e.g. how much the environment will light the object
  44827. * either through harmonics for rough material or through the refelction for shiny ones.
  44828. */
  44829. _this._environmentIntensity = 1.0;
  44830. /**
  44831. * This is a special control allowing the reduction of the specular highlights coming from the
  44832. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44833. */
  44834. _this._specularIntensity = 1.0;
  44835. /**
  44836. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44837. */
  44838. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44839. /**
  44840. * Debug Control allowing disabling the bump map on this material.
  44841. */
  44842. _this._disableBumpMap = false;
  44843. /**
  44844. * AKA Occlusion Texture Intensity in other nomenclature.
  44845. */
  44846. _this._ambientTextureStrength = 1.0;
  44847. /**
  44848. * The color of a material in ambient lighting.
  44849. */
  44850. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44851. /**
  44852. * AKA Diffuse Color in other nomenclature.
  44853. */
  44854. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44855. /**
  44856. * AKA Specular Color in other nomenclature.
  44857. */
  44858. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44859. /**
  44860. * The color applied when light is reflected from a material.
  44861. */
  44862. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44863. /**
  44864. * The color applied when light is emitted from a material.
  44865. */
  44866. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44867. /**
  44868. * AKA Glossiness in other nomenclature.
  44869. */
  44870. _this._microSurface = 0.9;
  44871. /**
  44872. * source material index of refraction (IOR)' / 'destination material IOR.
  44873. */
  44874. _this._indexOfRefraction = 0.66;
  44875. /**
  44876. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44877. */
  44878. _this._invertRefractionY = false;
  44879. /**
  44880. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44881. * Materials half opaque for instance using refraction could benefit from this control.
  44882. */
  44883. _this._linkRefractionWithTransparency = false;
  44884. /**
  44885. * Specifies that the material will use the light map as a show map.
  44886. */
  44887. _this._useLightmapAsShadowmap = false;
  44888. /**
  44889. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44890. * makes the reflect vector face the model (under horizon).
  44891. */
  44892. _this._useHorizonOcclusion = true;
  44893. /**
  44894. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44895. * too much the area relying on ambient texture to define their ambient occlusion.
  44896. */
  44897. _this._useRadianceOcclusion = true;
  44898. /**
  44899. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44900. */
  44901. _this._useAlphaFromAlbedoTexture = false;
  44902. /**
  44903. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44904. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44905. */
  44906. _this._useSpecularOverAlpha = true;
  44907. /**
  44908. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44909. */
  44910. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44911. /**
  44912. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44913. */
  44914. _this._useRoughnessFromMetallicTextureAlpha = true;
  44915. /**
  44916. * Specifies if the metallic texture contains the roughness information in its green channel.
  44917. */
  44918. _this._useRoughnessFromMetallicTextureGreen = false;
  44919. /**
  44920. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44921. */
  44922. _this._useMetallnessFromMetallicTextureBlue = false;
  44923. /**
  44924. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44925. */
  44926. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44927. /**
  44928. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44929. */
  44930. _this._useAmbientInGrayScale = false;
  44931. /**
  44932. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44933. * The material will try to infer what glossiness each pixel should be.
  44934. */
  44935. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44936. /**
  44937. * BJS is using an harcoded light falloff based on a manually sets up range.
  44938. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44939. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44940. */
  44941. _this._usePhysicalLightFalloff = true;
  44942. /**
  44943. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44944. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44945. */
  44946. _this._useRadianceOverAlpha = true;
  44947. /**
  44948. * Allows using an object space normal map (instead of tangent space).
  44949. */
  44950. _this._useObjectSpaceNormalMap = false;
  44951. /**
  44952. * Allows using the bump map in parallax mode.
  44953. */
  44954. _this._useParallax = false;
  44955. /**
  44956. * Allows using the bump map in parallax occlusion mode.
  44957. */
  44958. _this._useParallaxOcclusion = false;
  44959. /**
  44960. * Controls the scale bias of the parallax mode.
  44961. */
  44962. _this._parallaxScaleBias = 0.05;
  44963. /**
  44964. * If sets to true, disables all the lights affecting the material.
  44965. */
  44966. _this._disableLighting = false;
  44967. /**
  44968. * Number of Simultaneous lights allowed on the material.
  44969. */
  44970. _this._maxSimultaneousLights = 4;
  44971. /**
  44972. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44973. */
  44974. _this._invertNormalMapX = false;
  44975. /**
  44976. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44977. */
  44978. _this._invertNormalMapY = false;
  44979. /**
  44980. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44981. */
  44982. _this._twoSidedLighting = false;
  44983. /**
  44984. * Defines the alpha limits in alpha test mode.
  44985. */
  44986. _this._alphaCutOff = 0.4;
  44987. /**
  44988. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44989. */
  44990. _this._forceAlphaTest = false;
  44991. /**
  44992. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44993. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44994. */
  44995. _this._useAlphaFresnel = false;
  44996. /**
  44997. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44998. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44999. */
  45000. _this._useLinearAlphaFresnel = false;
  45001. /**
  45002. * The transparency mode of the material.
  45003. */
  45004. _this._transparencyMode = null;
  45005. /**
  45006. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45007. * from cos thetav and roughness:
  45008. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45009. */
  45010. _this._environmentBRDFTexture = null;
  45011. /**
  45012. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45013. */
  45014. _this._forceIrradianceInFragment = false;
  45015. /**
  45016. * Force normal to face away from face.
  45017. */
  45018. _this._forceNormalForward = false;
  45019. /**
  45020. * Enables specular anti aliasing in the PBR shader.
  45021. * It will both interacts on the Geometry for analytical and IBL lighting.
  45022. * It also prefilter the roughness map based on the bump values.
  45023. */
  45024. _this._enableSpecularAntiAliasing = false;
  45025. /**
  45026. * Stores the available render targets.
  45027. */
  45028. _this._renderTargets = new BABYLON.SmartArray(16);
  45029. /**
  45030. * Sets the global ambient color for the material used in lighting calculations.
  45031. */
  45032. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45033. /**
  45034. * If set to true, no lighting calculations will be applied.
  45035. */
  45036. _this._unlit = false;
  45037. // Setup the default processing configuration to the scene.
  45038. _this._attachImageProcessingConfiguration(null);
  45039. _this.getRenderTargetTextures = function () {
  45040. _this._renderTargets.reset();
  45041. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45042. _this._renderTargets.push(_this._reflectionTexture);
  45043. }
  45044. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45045. _this._renderTargets.push(_this._refractionTexture);
  45046. }
  45047. return _this._renderTargets;
  45048. };
  45049. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45050. return _this;
  45051. }
  45052. /**
  45053. * Attaches a new image processing configuration to the PBR Material.
  45054. * @param configuration
  45055. */
  45056. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45057. var _this = this;
  45058. if (configuration === this._imageProcessingConfiguration) {
  45059. return;
  45060. }
  45061. // Detaches observer.
  45062. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45063. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45064. }
  45065. // Pick the scene configuration if needed.
  45066. if (!configuration) {
  45067. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45068. }
  45069. else {
  45070. this._imageProcessingConfiguration = configuration;
  45071. }
  45072. // Attaches observer.
  45073. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45074. _this._markAllSubMeshesAsImageProcessingDirty();
  45075. });
  45076. };
  45077. /**
  45078. * Gets the name of the material class.
  45079. */
  45080. PBRBaseMaterial.prototype.getClassName = function () {
  45081. return "PBRBaseMaterial";
  45082. };
  45083. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45084. /**
  45085. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45086. */
  45087. get: function () {
  45088. return this._useLogarithmicDepth;
  45089. },
  45090. /**
  45091. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45092. */
  45093. set: function (value) {
  45094. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45095. },
  45096. enumerable: true,
  45097. configurable: true
  45098. });
  45099. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45100. /**
  45101. * Gets the current transparency mode.
  45102. */
  45103. get: function () {
  45104. return this._transparencyMode;
  45105. },
  45106. /**
  45107. * Sets the transparency mode of the material.
  45108. *
  45109. * | Value | Type | Description |
  45110. * | ----- | ----------------------------------- | ----------- |
  45111. * | 0 | OPAQUE | |
  45112. * | 1 | ALPHATEST | |
  45113. * | 2 | ALPHABLEND | |
  45114. * | 3 | ALPHATESTANDBLEND | |
  45115. *
  45116. */
  45117. set: function (value) {
  45118. if (this._transparencyMode === value) {
  45119. return;
  45120. }
  45121. this._transparencyMode = value;
  45122. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45123. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45129. /**
  45130. * Returns true if alpha blending should be disabled.
  45131. */
  45132. get: function () {
  45133. return (this._linkRefractionWithTransparency ||
  45134. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45135. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. /**
  45141. * Specifies whether or not this material should be rendered in alpha blend mode.
  45142. */
  45143. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45144. if (this._disableAlphaBlending) {
  45145. return false;
  45146. }
  45147. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45148. };
  45149. /**
  45150. * Specifies if the mesh will require alpha blending.
  45151. * @param mesh - BJS mesh.
  45152. */
  45153. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45154. if (this._disableAlphaBlending) {
  45155. return false;
  45156. }
  45157. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45158. };
  45159. /**
  45160. * Specifies whether or not this material should be rendered in alpha test mode.
  45161. */
  45162. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45163. if (this._forceAlphaTest) {
  45164. return true;
  45165. }
  45166. if (this._linkRefractionWithTransparency) {
  45167. return false;
  45168. }
  45169. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45170. };
  45171. /**
  45172. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45173. */
  45174. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45175. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45176. };
  45177. /**
  45178. * Gets the texture used for the alpha test.
  45179. */
  45180. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45181. return this._albedoTexture;
  45182. };
  45183. /**
  45184. * Specifies that the submesh is ready to be used.
  45185. * @param mesh - BJS mesh.
  45186. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45187. * @param useInstances - Specifies that instances should be used.
  45188. * @returns - boolean indicating that the submesh is ready or not.
  45189. */
  45190. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45191. if (subMesh.effect && this.isFrozen) {
  45192. if (this._wasPreviouslyReady) {
  45193. return true;
  45194. }
  45195. }
  45196. if (!subMesh._materialDefines) {
  45197. subMesh._materialDefines = new PBRMaterialDefines();
  45198. }
  45199. var defines = subMesh._materialDefines;
  45200. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45201. if (defines._renderId === this.getScene().getRenderId()) {
  45202. return true;
  45203. }
  45204. }
  45205. var scene = this.getScene();
  45206. var engine = scene.getEngine();
  45207. if (defines._areTexturesDirty) {
  45208. if (scene.texturesEnabled) {
  45209. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45210. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45211. return false;
  45212. }
  45213. }
  45214. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45215. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45216. return false;
  45217. }
  45218. }
  45219. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45220. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45221. return false;
  45222. }
  45223. }
  45224. var reflectionTexture = this._getReflectionTexture();
  45225. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45226. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45227. return false;
  45228. }
  45229. }
  45230. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45231. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45232. return false;
  45233. }
  45234. }
  45235. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45236. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45237. return false;
  45238. }
  45239. }
  45240. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45241. if (this._metallicTexture) {
  45242. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45243. return false;
  45244. }
  45245. }
  45246. else if (this._reflectivityTexture) {
  45247. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45248. return false;
  45249. }
  45250. }
  45251. if (this._microSurfaceTexture) {
  45252. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45253. return false;
  45254. }
  45255. }
  45256. }
  45257. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45258. // Bump texture cannot be not blocking.
  45259. if (!this._bumpTexture.isReady()) {
  45260. return false;
  45261. }
  45262. }
  45263. var refractionTexture = this._getRefractionTexture();
  45264. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45265. if (!refractionTexture.isReadyOrNotBlocking()) {
  45266. return false;
  45267. }
  45268. }
  45269. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45270. // This is blocking.
  45271. if (!this._environmentBRDFTexture.isReady()) {
  45272. return false;
  45273. }
  45274. }
  45275. }
  45276. }
  45277. if (defines._areImageProcessingDirty) {
  45278. if (!this._imageProcessingConfiguration.isReady()) {
  45279. return false;
  45280. }
  45281. }
  45282. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45283. mesh.createNormals(true);
  45284. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45285. }
  45286. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45287. if (effect) {
  45288. scene.resetCachedMaterial();
  45289. subMesh.setEffect(effect, defines);
  45290. this.buildUniformLayout();
  45291. }
  45292. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45293. return false;
  45294. }
  45295. defines._renderId = scene.getRenderId();
  45296. this._wasPreviouslyReady = true;
  45297. return true;
  45298. };
  45299. /**
  45300. * Specifies if the material uses metallic roughness workflow.
  45301. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45302. */
  45303. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45304. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45305. return true;
  45306. }
  45307. return false;
  45308. };
  45309. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45310. if (onCompiled === void 0) { onCompiled = null; }
  45311. if (onError === void 0) { onError = null; }
  45312. if (useInstances === void 0) { useInstances = null; }
  45313. if (useClipPlane === void 0) { useClipPlane = null; }
  45314. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45315. if (!defines.isDirty) {
  45316. return null;
  45317. }
  45318. defines.markAsProcessed();
  45319. var scene = this.getScene();
  45320. var engine = scene.getEngine();
  45321. // Fallbacks
  45322. var fallbacks = new BABYLON.EffectFallbacks();
  45323. var fallbackRank = 0;
  45324. if (defines.USESPHERICALINVERTEX) {
  45325. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45326. }
  45327. if (defines.FOG) {
  45328. fallbacks.addFallback(fallbackRank, "FOG");
  45329. }
  45330. if (defines.SPECULARAA) {
  45331. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45332. }
  45333. if (defines.POINTSIZE) {
  45334. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45335. }
  45336. if (defines.LOGARITHMICDEPTH) {
  45337. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45338. }
  45339. if (defines.PARALLAX) {
  45340. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45341. }
  45342. if (defines.PARALLAXOCCLUSION) {
  45343. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45344. }
  45345. if (defines.ENVIRONMENTBRDF) {
  45346. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45347. }
  45348. if (defines.TANGENT) {
  45349. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45350. }
  45351. if (defines.BUMP) {
  45352. fallbacks.addFallback(fallbackRank++, "BUMP");
  45353. }
  45354. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45355. if (defines.SPECULARTERM) {
  45356. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45357. }
  45358. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45359. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45360. }
  45361. if (defines.LIGHTMAP) {
  45362. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45363. }
  45364. if (defines.NORMAL) {
  45365. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45366. }
  45367. if (defines.AMBIENT) {
  45368. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45369. }
  45370. if (defines.EMISSIVE) {
  45371. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45372. }
  45373. if (defines.VERTEXCOLOR) {
  45374. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45375. }
  45376. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45377. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45378. }
  45379. if (defines.MORPHTARGETS) {
  45380. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45381. }
  45382. //Attributes
  45383. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45384. if (defines.NORMAL) {
  45385. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45386. }
  45387. if (defines.TANGENT) {
  45388. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45389. }
  45390. if (defines.UV1) {
  45391. attribs.push(BABYLON.VertexBuffer.UVKind);
  45392. }
  45393. if (defines.UV2) {
  45394. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45395. }
  45396. if (defines.VERTEXCOLOR) {
  45397. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45398. }
  45399. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45400. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45401. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45402. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45403. "vFogInfos", "vFogColor", "pointSize",
  45404. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45405. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45406. "mBones",
  45407. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45408. "vLightingIntensity",
  45409. "logarithmicDepthConstant",
  45410. "vSphericalX", "vSphericalY", "vSphericalZ",
  45411. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45412. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45413. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45414. "vTangentSpaceParams"
  45415. ];
  45416. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45417. "bumpSampler", "lightmapSampler", "opacitySampler",
  45418. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45419. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45420. "microSurfaceSampler", "environmentBrdfSampler"];
  45421. var uniformBuffers = ["Material", "Scene"];
  45422. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45423. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45424. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45425. uniformsNames: uniforms,
  45426. uniformBuffersNames: uniformBuffers,
  45427. samplers: samplers,
  45428. defines: defines,
  45429. maxSimultaneousLights: this._maxSimultaneousLights
  45430. });
  45431. var join = defines.toString();
  45432. return engine.createEffect("pbr", {
  45433. attributes: attribs,
  45434. uniformsNames: uniforms,
  45435. uniformBuffersNames: uniformBuffers,
  45436. samplers: samplers,
  45437. defines: join,
  45438. fallbacks: fallbacks,
  45439. onCompiled: onCompiled,
  45440. onError: onError,
  45441. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45442. }, engine);
  45443. };
  45444. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45445. if (useInstances === void 0) { useInstances = null; }
  45446. if (useClipPlane === void 0) { useClipPlane = null; }
  45447. var scene = this.getScene();
  45448. var engine = scene.getEngine();
  45449. // Lights
  45450. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45451. defines._needNormals = true;
  45452. // Textures
  45453. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45454. if (defines._areTexturesDirty) {
  45455. defines._needUVs = false;
  45456. if (scene.texturesEnabled) {
  45457. if (scene.getEngine().getCaps().textureLOD) {
  45458. defines.LODBASEDMICROSFURACE = true;
  45459. }
  45460. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45461. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45462. }
  45463. else {
  45464. defines.ALBEDO = false;
  45465. }
  45466. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45467. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45468. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45469. }
  45470. else {
  45471. defines.AMBIENT = false;
  45472. }
  45473. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45474. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45475. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45476. }
  45477. else {
  45478. defines.OPACITY = false;
  45479. }
  45480. var reflectionTexture = this._getReflectionTexture();
  45481. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45482. defines.REFLECTION = true;
  45483. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45484. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45485. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45486. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45487. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45488. defines.INVERTCUBICMAP = true;
  45489. }
  45490. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45491. switch (reflectionTexture.coordinatesMode) {
  45492. case BABYLON.Texture.EXPLICIT_MODE:
  45493. defines.REFLECTIONMAP_EXPLICIT = true;
  45494. break;
  45495. case BABYLON.Texture.PLANAR_MODE:
  45496. defines.REFLECTIONMAP_PLANAR = true;
  45497. break;
  45498. case BABYLON.Texture.PROJECTION_MODE:
  45499. defines.REFLECTIONMAP_PROJECTION = true;
  45500. break;
  45501. case BABYLON.Texture.SKYBOX_MODE:
  45502. defines.REFLECTIONMAP_SKYBOX = true;
  45503. break;
  45504. case BABYLON.Texture.SPHERICAL_MODE:
  45505. defines.REFLECTIONMAP_SPHERICAL = true;
  45506. break;
  45507. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45508. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45509. break;
  45510. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45511. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45512. break;
  45513. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45514. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45515. break;
  45516. case BABYLON.Texture.CUBIC_MODE:
  45517. case BABYLON.Texture.INVCUBIC_MODE:
  45518. default:
  45519. defines.REFLECTIONMAP_CUBIC = true;
  45520. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45521. break;
  45522. }
  45523. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45524. if (reflectionTexture.sphericalPolynomial) {
  45525. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45526. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45527. defines.USESPHERICALINVERTEX = false;
  45528. }
  45529. else {
  45530. defines.USESPHERICALINVERTEX = true;
  45531. }
  45532. }
  45533. }
  45534. }
  45535. else {
  45536. defines.REFLECTION = false;
  45537. defines.REFLECTIONMAP_3D = false;
  45538. defines.REFLECTIONMAP_SPHERICAL = false;
  45539. defines.REFLECTIONMAP_PLANAR = false;
  45540. defines.REFLECTIONMAP_CUBIC = false;
  45541. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45542. defines.REFLECTIONMAP_PROJECTION = false;
  45543. defines.REFLECTIONMAP_SKYBOX = false;
  45544. defines.REFLECTIONMAP_EXPLICIT = false;
  45545. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45546. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45547. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45548. defines.INVERTCUBICMAP = false;
  45549. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45550. defines.USESPHERICALINVERTEX = false;
  45551. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45552. defines.LODINREFLECTIONALPHA = false;
  45553. defines.GAMMAREFLECTION = false;
  45554. defines.RGBDREFLECTION = false;
  45555. }
  45556. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45557. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45558. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45559. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45560. }
  45561. else {
  45562. defines.LIGHTMAP = false;
  45563. }
  45564. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45565. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45566. }
  45567. else {
  45568. defines.EMISSIVE = false;
  45569. }
  45570. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45571. if (this._metallicTexture) {
  45572. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45573. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45574. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45575. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45576. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45577. }
  45578. else if (this._reflectivityTexture) {
  45579. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45580. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45581. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45582. }
  45583. else {
  45584. defines.REFLECTIVITY = false;
  45585. }
  45586. if (this._microSurfaceTexture) {
  45587. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45588. }
  45589. else {
  45590. defines.MICROSURFACEMAP = false;
  45591. }
  45592. }
  45593. else {
  45594. defines.REFLECTIVITY = false;
  45595. defines.MICROSURFACEMAP = false;
  45596. }
  45597. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45598. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45599. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45600. defines.PARALLAX = true;
  45601. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45602. }
  45603. else {
  45604. defines.PARALLAX = false;
  45605. }
  45606. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45607. }
  45608. else {
  45609. defines.BUMP = false;
  45610. }
  45611. var refractionTexture = this._getRefractionTexture();
  45612. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45613. defines.REFRACTION = true;
  45614. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45615. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45616. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45617. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45618. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45619. if (this._linkRefractionWithTransparency) {
  45620. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45621. }
  45622. }
  45623. else {
  45624. defines.REFRACTION = false;
  45625. }
  45626. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45627. defines.ENVIRONMENTBRDF = true;
  45628. }
  45629. else {
  45630. defines.ENVIRONMENTBRDF = false;
  45631. }
  45632. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45633. defines.ALPHAFROMALBEDO = true;
  45634. }
  45635. else {
  45636. defines.ALPHAFROMALBEDO = false;
  45637. }
  45638. }
  45639. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45640. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45641. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45642. if (!this.backFaceCulling && this._twoSidedLighting) {
  45643. defines.TWOSIDEDLIGHTING = true;
  45644. }
  45645. else {
  45646. defines.TWOSIDEDLIGHTING = false;
  45647. }
  45648. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45649. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45650. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45651. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45652. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45653. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45654. }
  45655. if (defines._areImageProcessingDirty) {
  45656. this._imageProcessingConfiguration.prepareDefines(defines);
  45657. }
  45658. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45659. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45660. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45661. // Misc.
  45662. if (defines._areMiscDirty) {
  45663. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45664. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45665. }
  45666. // Values that need to be evaluated on every frame
  45667. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45668. // Attribs
  45669. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45670. };
  45671. /**
  45672. * Force shader compilation
  45673. */
  45674. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45675. var _this = this;
  45676. var localOptions = __assign({ clipPlane: false }, options);
  45677. var defines = new PBRMaterialDefines();
  45678. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45679. if (effect.isReady()) {
  45680. if (onCompiled) {
  45681. onCompiled(this);
  45682. }
  45683. }
  45684. else {
  45685. effect.onCompileObservable.add(function () {
  45686. if (onCompiled) {
  45687. onCompiled(_this);
  45688. }
  45689. });
  45690. }
  45691. };
  45692. /**
  45693. * Initializes the uniform buffer layout for the shader.
  45694. */
  45695. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45696. // Order is important !
  45697. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45698. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45699. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45700. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45701. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45702. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45703. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45704. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45705. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45706. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45707. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45708. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45709. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45710. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45711. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45712. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45713. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45714. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45715. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45716. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45717. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45718. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45719. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45720. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45721. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45722. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45723. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45724. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45725. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45726. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45727. this._uniformBuffer.addUniform("pointSize", 1);
  45728. this._uniformBuffer.create();
  45729. };
  45730. /**
  45731. * Unbinds the textures.
  45732. */
  45733. PBRBaseMaterial.prototype.unbind = function () {
  45734. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45735. this._uniformBuffer.setTexture("reflectionSampler", null);
  45736. }
  45737. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45738. this._uniformBuffer.setTexture("refractionSampler", null);
  45739. }
  45740. _super.prototype.unbind.call(this);
  45741. };
  45742. /**
  45743. * Binds the submesh data.
  45744. * @param world - The world matrix.
  45745. * @param mesh - The BJS mesh.
  45746. * @param subMesh - A submesh of the BJS mesh.
  45747. */
  45748. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45749. var scene = this.getScene();
  45750. var defines = subMesh._materialDefines;
  45751. if (!defines) {
  45752. return;
  45753. }
  45754. var effect = subMesh.effect;
  45755. if (!effect) {
  45756. return;
  45757. }
  45758. this._activeEffect = effect;
  45759. // Matrices
  45760. this.bindOnlyWorldMatrix(world);
  45761. // Normal Matrix
  45762. if (defines.OBJECTSPACE_NORMALMAP) {
  45763. world.toNormalMatrix(this._normalMatrix);
  45764. this.bindOnlyNormalMatrix(this._normalMatrix);
  45765. }
  45766. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45767. // Bones
  45768. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45769. var reflectionTexture = null;
  45770. if (mustRebind) {
  45771. this._uniformBuffer.bindToEffect(effect, "Material");
  45772. this.bindViewProjection(effect);
  45773. reflectionTexture = this._getReflectionTexture();
  45774. var refractionTexture = this._getRefractionTexture();
  45775. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45776. // Texture uniforms
  45777. if (scene.texturesEnabled) {
  45778. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45779. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45780. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45781. }
  45782. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45783. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45784. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45785. }
  45786. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45787. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45788. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45789. }
  45790. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45791. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45792. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45793. if (reflectionTexture.boundingBoxSize) {
  45794. var cubeTexture = reflectionTexture;
  45795. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45796. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45797. }
  45798. var polynomials = reflectionTexture.sphericalPolynomial;
  45799. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45800. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45801. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45802. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45803. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45804. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45805. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45806. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45807. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45808. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45809. }
  45810. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45811. }
  45812. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45813. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45814. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45815. }
  45816. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45817. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45818. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45819. }
  45820. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45821. if (this._metallicTexture) {
  45822. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45823. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45824. }
  45825. else if (this._reflectivityTexture) {
  45826. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45827. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45828. }
  45829. if (this._microSurfaceTexture) {
  45830. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45831. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45832. }
  45833. }
  45834. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45835. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45836. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45837. if (scene._mirroredCameraPosition) {
  45838. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45839. }
  45840. else {
  45841. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45842. }
  45843. }
  45844. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45845. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45846. var depth = 1.0;
  45847. if (!refractionTexture.isCube) {
  45848. if (refractionTexture.depth) {
  45849. depth = refractionTexture.depth;
  45850. }
  45851. }
  45852. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45853. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45854. }
  45855. }
  45856. // Point size
  45857. if (this.pointsCloud) {
  45858. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45859. }
  45860. // Colors
  45861. if (defines.METALLICWORKFLOW) {
  45862. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45863. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45864. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45865. }
  45866. else {
  45867. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45868. }
  45869. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45870. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45871. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45872. // Misc
  45873. this._lightingInfos.x = this._directIntensity;
  45874. this._lightingInfos.y = this._emissiveIntensity;
  45875. this._lightingInfos.z = this._environmentIntensity;
  45876. this._lightingInfos.w = this._specularIntensity;
  45877. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45878. }
  45879. // Textures
  45880. if (scene.texturesEnabled) {
  45881. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45882. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45883. }
  45884. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45885. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45886. }
  45887. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45888. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45889. }
  45890. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45891. if (defines.LODBASEDMICROSFURACE) {
  45892. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45893. }
  45894. else {
  45895. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45896. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45897. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45898. }
  45899. }
  45900. if (defines.ENVIRONMENTBRDF) {
  45901. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45902. }
  45903. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45904. if (defines.LODBASEDMICROSFURACE) {
  45905. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45906. }
  45907. else {
  45908. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45909. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45910. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45911. }
  45912. }
  45913. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45914. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45915. }
  45916. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45917. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45918. }
  45919. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45920. if (this._metallicTexture) {
  45921. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45922. }
  45923. else if (this._reflectivityTexture) {
  45924. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45925. }
  45926. if (this._microSurfaceTexture) {
  45927. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45928. }
  45929. }
  45930. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45931. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45932. }
  45933. }
  45934. // Clip plane
  45935. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45936. // Colors
  45937. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45938. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45939. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45940. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45941. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45942. }
  45943. if (mustRebind || !this.isFrozen) {
  45944. // Lights
  45945. if (scene.lightsEnabled && !this._disableLighting) {
  45946. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45947. }
  45948. // View
  45949. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45950. this.bindView(effect);
  45951. }
  45952. // Fog
  45953. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45954. // Morph targets
  45955. if (defines.NUM_MORPH_INFLUENCERS) {
  45956. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45957. }
  45958. // image processing
  45959. this._imageProcessingConfiguration.bind(this._activeEffect);
  45960. // Log. depth
  45961. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45962. }
  45963. this._uniformBuffer.update();
  45964. this._afterBind(mesh, this._activeEffect);
  45965. };
  45966. /**
  45967. * Returns the animatable textures.
  45968. * @returns - Array of animatable textures.
  45969. */
  45970. PBRBaseMaterial.prototype.getAnimatables = function () {
  45971. var results = [];
  45972. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45973. results.push(this._albedoTexture);
  45974. }
  45975. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45976. results.push(this._ambientTexture);
  45977. }
  45978. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45979. results.push(this._opacityTexture);
  45980. }
  45981. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45982. results.push(this._reflectionTexture);
  45983. }
  45984. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45985. results.push(this._emissiveTexture);
  45986. }
  45987. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45988. results.push(this._metallicTexture);
  45989. }
  45990. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45991. results.push(this._reflectivityTexture);
  45992. }
  45993. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45994. results.push(this._bumpTexture);
  45995. }
  45996. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45997. results.push(this._lightmapTexture);
  45998. }
  45999. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46000. results.push(this._refractionTexture);
  46001. }
  46002. return results;
  46003. };
  46004. /**
  46005. * Returns the texture used for reflections.
  46006. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46007. */
  46008. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46009. if (this._reflectionTexture) {
  46010. return this._reflectionTexture;
  46011. }
  46012. return this.getScene().environmentTexture;
  46013. };
  46014. /**
  46015. * Returns the texture used for refraction or null if none is used.
  46016. * @returns - Refection texture if present. If no refraction texture and refraction
  46017. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46018. */
  46019. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46020. if (this._refractionTexture) {
  46021. return this._refractionTexture;
  46022. }
  46023. if (this._linkRefractionWithTransparency) {
  46024. return this.getScene().environmentTexture;
  46025. }
  46026. return null;
  46027. };
  46028. /**
  46029. * Disposes the resources of the material.
  46030. * @param forceDisposeEffect - Forces the disposal of effects.
  46031. * @param forceDisposeTextures - Forces the disposal of all textures.
  46032. */
  46033. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46034. if (forceDisposeTextures) {
  46035. if (this._albedoTexture) {
  46036. this._albedoTexture.dispose();
  46037. }
  46038. if (this._ambientTexture) {
  46039. this._ambientTexture.dispose();
  46040. }
  46041. if (this._opacityTexture) {
  46042. this._opacityTexture.dispose();
  46043. }
  46044. if (this._reflectionTexture) {
  46045. this._reflectionTexture.dispose();
  46046. }
  46047. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46048. this._environmentBRDFTexture.dispose();
  46049. }
  46050. if (this._emissiveTexture) {
  46051. this._emissiveTexture.dispose();
  46052. }
  46053. if (this._metallicTexture) {
  46054. this._metallicTexture.dispose();
  46055. }
  46056. if (this._reflectivityTexture) {
  46057. this._reflectivityTexture.dispose();
  46058. }
  46059. if (this._bumpTexture) {
  46060. this._bumpTexture.dispose();
  46061. }
  46062. if (this._lightmapTexture) {
  46063. this._lightmapTexture.dispose();
  46064. }
  46065. if (this._refractionTexture) {
  46066. this._refractionTexture.dispose();
  46067. }
  46068. }
  46069. this._renderTargets.dispose();
  46070. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46071. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46072. }
  46073. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46074. };
  46075. /**
  46076. * Stores the reflectivity values based on metallic roughness workflow.
  46077. */
  46078. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46079. __decorate([
  46080. BABYLON.serializeAsImageProcessingConfiguration()
  46081. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46082. __decorate([
  46083. BABYLON.serialize()
  46084. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46085. __decorate([
  46086. BABYLON.serialize()
  46087. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46088. return PBRBaseMaterial;
  46089. }(BABYLON.PushMaterial));
  46090. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46091. })(BABYLON || (BABYLON = {}));
  46092. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46093. var BABYLON;
  46094. (function (BABYLON) {
  46095. /**
  46096. * The Physically based simple base material of BJS.
  46097. *
  46098. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46099. * It is used as the base class for both the specGloss and metalRough conventions.
  46100. */
  46101. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46102. __extends(PBRBaseSimpleMaterial, _super);
  46103. /**
  46104. * Instantiates a new PBRMaterial instance.
  46105. *
  46106. * @param name The material name
  46107. * @param scene The scene the material will be use in.
  46108. */
  46109. function PBRBaseSimpleMaterial(name, scene) {
  46110. var _this = _super.call(this, name, scene) || this;
  46111. /**
  46112. * Number of Simultaneous lights allowed on the material.
  46113. */
  46114. _this.maxSimultaneousLights = 4;
  46115. /**
  46116. * If sets to true, disables all the lights affecting the material.
  46117. */
  46118. _this.disableLighting = false;
  46119. /**
  46120. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46121. */
  46122. _this.invertNormalMapX = false;
  46123. /**
  46124. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46125. */
  46126. _this.invertNormalMapY = false;
  46127. /**
  46128. * Emissivie color used to self-illuminate the model.
  46129. */
  46130. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46131. /**
  46132. * Occlusion Channel Strenght.
  46133. */
  46134. _this.occlusionStrength = 1.0;
  46135. _this.useLightmapAsShadowmap = false;
  46136. _this._useAlphaFromAlbedoTexture = true;
  46137. _this._useAmbientInGrayScale = true;
  46138. return _this;
  46139. }
  46140. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46141. /**
  46142. * Gets the current double sided mode.
  46143. */
  46144. get: function () {
  46145. return this._twoSidedLighting;
  46146. },
  46147. /**
  46148. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46149. */
  46150. set: function (value) {
  46151. if (this._twoSidedLighting === value) {
  46152. return;
  46153. }
  46154. this._twoSidedLighting = value;
  46155. this.backFaceCulling = !value;
  46156. this._markAllSubMeshesAsTexturesDirty();
  46157. },
  46158. enumerable: true,
  46159. configurable: true
  46160. });
  46161. /**
  46162. * Return the active textures of the material.
  46163. */
  46164. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46165. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46166. if (this.environmentTexture) {
  46167. activeTextures.push(this.environmentTexture);
  46168. }
  46169. if (this.normalTexture) {
  46170. activeTextures.push(this.normalTexture);
  46171. }
  46172. if (this.emissiveTexture) {
  46173. activeTextures.push(this.emissiveTexture);
  46174. }
  46175. if (this.occlusionTexture) {
  46176. activeTextures.push(this.occlusionTexture);
  46177. }
  46178. if (this.lightmapTexture) {
  46179. activeTextures.push(this.lightmapTexture);
  46180. }
  46181. return activeTextures;
  46182. };
  46183. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46184. if (_super.prototype.hasTexture.call(this, texture)) {
  46185. return true;
  46186. }
  46187. if (this.lightmapTexture === texture) {
  46188. return true;
  46189. }
  46190. return false;
  46191. };
  46192. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46193. return "PBRBaseSimpleMaterial";
  46194. };
  46195. __decorate([
  46196. BABYLON.serialize(),
  46197. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46198. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46199. __decorate([
  46200. BABYLON.serialize(),
  46201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46202. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46203. __decorate([
  46204. BABYLON.serializeAsTexture(),
  46205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46206. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46207. __decorate([
  46208. BABYLON.serialize(),
  46209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46210. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46211. __decorate([
  46212. BABYLON.serialize(),
  46213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46214. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46215. __decorate([
  46216. BABYLON.serializeAsTexture(),
  46217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46218. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46219. __decorate([
  46220. BABYLON.serializeAsColor3("emissive"),
  46221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46222. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46223. __decorate([
  46224. BABYLON.serializeAsTexture(),
  46225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46226. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46227. __decorate([
  46228. BABYLON.serialize(),
  46229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46230. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46231. __decorate([
  46232. BABYLON.serializeAsTexture(),
  46233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46234. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46235. __decorate([
  46236. BABYLON.serialize(),
  46237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46238. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46239. __decorate([
  46240. BABYLON.serialize()
  46241. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46242. __decorate([
  46243. BABYLON.serializeAsTexture(),
  46244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46245. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46246. __decorate([
  46247. BABYLON.serialize(),
  46248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46249. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46250. return PBRBaseSimpleMaterial;
  46251. }(BABYLON.PBRBaseMaterial));
  46252. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46253. })(BABYLON || (BABYLON = {}));
  46254. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46255. var BABYLON;
  46256. (function (BABYLON) {
  46257. /**
  46258. * The Physically based material of BJS.
  46259. *
  46260. * This offers the main features of a standard PBR material.
  46261. * For more information, please refer to the documentation :
  46262. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46263. */
  46264. var PBRMaterial = /** @class */ (function (_super) {
  46265. __extends(PBRMaterial, _super);
  46266. /**
  46267. * Instantiates a new PBRMaterial instance.
  46268. *
  46269. * @param name The material name
  46270. * @param scene The scene the material will be use in.
  46271. */
  46272. function PBRMaterial(name, scene) {
  46273. var _this = _super.call(this, name, scene) || this;
  46274. /**
  46275. * Intensity of the direct lights e.g. the four lights available in your scene.
  46276. * This impacts both the direct diffuse and specular highlights.
  46277. */
  46278. _this.directIntensity = 1.0;
  46279. /**
  46280. * Intensity of the emissive part of the material.
  46281. * This helps controlling the emissive effect without modifying the emissive color.
  46282. */
  46283. _this.emissiveIntensity = 1.0;
  46284. /**
  46285. * Intensity of the environment e.g. how much the environment will light the object
  46286. * either through harmonics for rough material or through the refelction for shiny ones.
  46287. */
  46288. _this.environmentIntensity = 1.0;
  46289. /**
  46290. * This is a special control allowing the reduction of the specular highlights coming from the
  46291. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46292. */
  46293. _this.specularIntensity = 1.0;
  46294. /**
  46295. * Debug Control allowing disabling the bump map on this material.
  46296. */
  46297. _this.disableBumpMap = false;
  46298. /**
  46299. * AKA Occlusion Texture Intensity in other nomenclature.
  46300. */
  46301. _this.ambientTextureStrength = 1.0;
  46302. /**
  46303. * The color of a material in ambient lighting.
  46304. */
  46305. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46306. /**
  46307. * AKA Diffuse Color in other nomenclature.
  46308. */
  46309. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46310. /**
  46311. * AKA Specular Color in other nomenclature.
  46312. */
  46313. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46314. /**
  46315. * The color reflected from the material.
  46316. */
  46317. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46318. /**
  46319. * The color emitted from the material.
  46320. */
  46321. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46322. /**
  46323. * AKA Glossiness in other nomenclature.
  46324. */
  46325. _this.microSurface = 1.0;
  46326. /**
  46327. * source material index of refraction (IOR)' / 'destination material IOR.
  46328. */
  46329. _this.indexOfRefraction = 0.66;
  46330. /**
  46331. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46332. */
  46333. _this.invertRefractionY = false;
  46334. /**
  46335. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46336. * Materials half opaque for instance using refraction could benefit from this control.
  46337. */
  46338. _this.linkRefractionWithTransparency = false;
  46339. _this.useLightmapAsShadowmap = false;
  46340. /**
  46341. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46342. */
  46343. _this.useAlphaFromAlbedoTexture = false;
  46344. /**
  46345. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46346. */
  46347. _this.forceAlphaTest = false;
  46348. /**
  46349. * Defines the alpha limits in alpha test mode.
  46350. */
  46351. _this.alphaCutOff = 0.4;
  46352. /**
  46353. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46354. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46355. */
  46356. _this.useSpecularOverAlpha = true;
  46357. /**
  46358. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46359. */
  46360. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46361. /**
  46362. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46363. */
  46364. _this.useRoughnessFromMetallicTextureAlpha = true;
  46365. /**
  46366. * Specifies if the metallic texture contains the roughness information in its green channel.
  46367. */
  46368. _this.useRoughnessFromMetallicTextureGreen = false;
  46369. /**
  46370. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46371. */
  46372. _this.useMetallnessFromMetallicTextureBlue = false;
  46373. /**
  46374. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46375. */
  46376. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46377. /**
  46378. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46379. */
  46380. _this.useAmbientInGrayScale = false;
  46381. /**
  46382. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46383. * The material will try to infer what glossiness each pixel should be.
  46384. */
  46385. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46386. /**
  46387. * BJS is using an harcoded light falloff based on a manually sets up range.
  46388. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46389. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46390. */
  46391. _this.usePhysicalLightFalloff = true;
  46392. /**
  46393. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46394. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46395. */
  46396. _this.useRadianceOverAlpha = true;
  46397. /**
  46398. * Allows using an object space normal map (instead of tangent space).
  46399. */
  46400. _this.useObjectSpaceNormalMap = false;
  46401. /**
  46402. * Allows using the bump map in parallax mode.
  46403. */
  46404. _this.useParallax = false;
  46405. /**
  46406. * Allows using the bump map in parallax occlusion mode.
  46407. */
  46408. _this.useParallaxOcclusion = false;
  46409. /**
  46410. * Controls the scale bias of the parallax mode.
  46411. */
  46412. _this.parallaxScaleBias = 0.05;
  46413. /**
  46414. * If sets to true, disables all the lights affecting the material.
  46415. */
  46416. _this.disableLighting = false;
  46417. /**
  46418. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46419. */
  46420. _this.forceIrradianceInFragment = false;
  46421. /**
  46422. * Number of Simultaneous lights allowed on the material.
  46423. */
  46424. _this.maxSimultaneousLights = 4;
  46425. /**
  46426. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46427. */
  46428. _this.invertNormalMapX = false;
  46429. /**
  46430. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46431. */
  46432. _this.invertNormalMapY = false;
  46433. /**
  46434. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46435. */
  46436. _this.twoSidedLighting = false;
  46437. /**
  46438. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46439. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46440. */
  46441. _this.useAlphaFresnel = false;
  46442. /**
  46443. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46444. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46445. */
  46446. _this.useLinearAlphaFresnel = false;
  46447. /**
  46448. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46449. * And/Or occlude the blended part.
  46450. */
  46451. _this.environmentBRDFTexture = null;
  46452. /**
  46453. * Force normal to face away from face.
  46454. */
  46455. _this.forceNormalForward = false;
  46456. /**
  46457. * Enables specular anti aliasing in the PBR shader.
  46458. * It will both interacts on the Geometry for analytical and IBL lighting.
  46459. * It also prefilter the roughness map based on the bump values.
  46460. */
  46461. _this.enableSpecularAntiAliasing = false;
  46462. /**
  46463. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46464. * makes the reflect vector face the model (under horizon).
  46465. */
  46466. _this.useHorizonOcclusion = true;
  46467. /**
  46468. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46469. * too much the area relying on ambient texture to define their ambient occlusion.
  46470. */
  46471. _this.useRadianceOcclusion = true;
  46472. /**
  46473. * If set to true, no lighting calculations will be applied.
  46474. */
  46475. _this.unlit = false;
  46476. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46477. return _this;
  46478. }
  46479. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46480. /**
  46481. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46482. */
  46483. get: function () {
  46484. return this._PBRMATERIAL_OPAQUE;
  46485. },
  46486. enumerable: true,
  46487. configurable: true
  46488. });
  46489. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46490. /**
  46491. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46492. */
  46493. get: function () {
  46494. return this._PBRMATERIAL_ALPHATEST;
  46495. },
  46496. enumerable: true,
  46497. configurable: true
  46498. });
  46499. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46500. /**
  46501. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46502. */
  46503. get: function () {
  46504. return this._PBRMATERIAL_ALPHABLEND;
  46505. },
  46506. enumerable: true,
  46507. configurable: true
  46508. });
  46509. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46510. /**
  46511. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46512. * They are also discarded below the alpha cutoff threshold to improve performances.
  46513. */
  46514. get: function () {
  46515. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46516. },
  46517. enumerable: true,
  46518. configurable: true
  46519. });
  46520. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46521. /**
  46522. * Gets the image processing configuration used either in this material.
  46523. */
  46524. get: function () {
  46525. return this._imageProcessingConfiguration;
  46526. },
  46527. /**
  46528. * Sets the Default image processing configuration used either in the this material.
  46529. *
  46530. * If sets to null, the scene one is in use.
  46531. */
  46532. set: function (value) {
  46533. this._attachImageProcessingConfiguration(value);
  46534. // Ensure the effect will be rebuilt.
  46535. this._markAllSubMeshesAsTexturesDirty();
  46536. },
  46537. enumerable: true,
  46538. configurable: true
  46539. });
  46540. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46541. /**
  46542. * Gets wether the color curves effect is enabled.
  46543. */
  46544. get: function () {
  46545. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46546. },
  46547. /**
  46548. * Sets wether the color curves effect is enabled.
  46549. */
  46550. set: function (value) {
  46551. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46552. },
  46553. enumerable: true,
  46554. configurable: true
  46555. });
  46556. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46557. /**
  46558. * Gets wether the color grading effect is enabled.
  46559. */
  46560. get: function () {
  46561. return this.imageProcessingConfiguration.colorGradingEnabled;
  46562. },
  46563. /**
  46564. * Gets wether the color grading effect is enabled.
  46565. */
  46566. set: function (value) {
  46567. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46568. },
  46569. enumerable: true,
  46570. configurable: true
  46571. });
  46572. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46573. /**
  46574. * Gets wether tonemapping is enabled or not.
  46575. */
  46576. get: function () {
  46577. return this._imageProcessingConfiguration.toneMappingEnabled;
  46578. },
  46579. /**
  46580. * Sets wether tonemapping is enabled or not
  46581. */
  46582. set: function (value) {
  46583. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46584. },
  46585. enumerable: true,
  46586. configurable: true
  46587. });
  46588. ;
  46589. ;
  46590. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46591. /**
  46592. * The camera exposure used on this material.
  46593. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46594. * This corresponds to a photographic exposure.
  46595. */
  46596. get: function () {
  46597. return this._imageProcessingConfiguration.exposure;
  46598. },
  46599. /**
  46600. * The camera exposure used on this material.
  46601. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46602. * This corresponds to a photographic exposure.
  46603. */
  46604. set: function (value) {
  46605. this._imageProcessingConfiguration.exposure = value;
  46606. },
  46607. enumerable: true,
  46608. configurable: true
  46609. });
  46610. ;
  46611. ;
  46612. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46613. /**
  46614. * Gets The camera contrast used on this material.
  46615. */
  46616. get: function () {
  46617. return this._imageProcessingConfiguration.contrast;
  46618. },
  46619. /**
  46620. * Sets The camera contrast used on this material.
  46621. */
  46622. set: function (value) {
  46623. this._imageProcessingConfiguration.contrast = value;
  46624. },
  46625. enumerable: true,
  46626. configurable: true
  46627. });
  46628. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46629. /**
  46630. * Gets the Color Grading 2D Lookup Texture.
  46631. */
  46632. get: function () {
  46633. return this._imageProcessingConfiguration.colorGradingTexture;
  46634. },
  46635. /**
  46636. * Sets the Color Grading 2D Lookup Texture.
  46637. */
  46638. set: function (value) {
  46639. this._imageProcessingConfiguration.colorGradingTexture = value;
  46640. },
  46641. enumerable: true,
  46642. configurable: true
  46643. });
  46644. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46645. /**
  46646. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46647. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46648. * 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;
  46649. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46650. */
  46651. get: function () {
  46652. return this._imageProcessingConfiguration.colorCurves;
  46653. },
  46654. /**
  46655. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46656. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46657. * 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;
  46658. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46659. */
  46660. set: function (value) {
  46661. this._imageProcessingConfiguration.colorCurves = value;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. /**
  46667. * Returns the name of this material class.
  46668. */
  46669. PBRMaterial.prototype.getClassName = function () {
  46670. return "PBRMaterial";
  46671. };
  46672. /**
  46673. * Returns an array of the actively used textures.
  46674. * @returns - Array of BaseTextures
  46675. */
  46676. PBRMaterial.prototype.getActiveTextures = function () {
  46677. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46678. if (this._albedoTexture) {
  46679. activeTextures.push(this._albedoTexture);
  46680. }
  46681. if (this._ambientTexture) {
  46682. activeTextures.push(this._ambientTexture);
  46683. }
  46684. if (this._opacityTexture) {
  46685. activeTextures.push(this._opacityTexture);
  46686. }
  46687. if (this._reflectionTexture) {
  46688. activeTextures.push(this._reflectionTexture);
  46689. }
  46690. if (this._emissiveTexture) {
  46691. activeTextures.push(this._emissiveTexture);
  46692. }
  46693. if (this._reflectivityTexture) {
  46694. activeTextures.push(this._reflectivityTexture);
  46695. }
  46696. if (this._metallicTexture) {
  46697. activeTextures.push(this._metallicTexture);
  46698. }
  46699. if (this._microSurfaceTexture) {
  46700. activeTextures.push(this._microSurfaceTexture);
  46701. }
  46702. if (this._bumpTexture) {
  46703. activeTextures.push(this._bumpTexture);
  46704. }
  46705. if (this._lightmapTexture) {
  46706. activeTextures.push(this._lightmapTexture);
  46707. }
  46708. if (this._refractionTexture) {
  46709. activeTextures.push(this._refractionTexture);
  46710. }
  46711. return activeTextures;
  46712. };
  46713. /**
  46714. * Checks to see if a texture is used in the material.
  46715. * @param texture - Base texture to use.
  46716. * @returns - Boolean specifying if a texture is used in the material.
  46717. */
  46718. PBRMaterial.prototype.hasTexture = function (texture) {
  46719. if (_super.prototype.hasTexture.call(this, texture)) {
  46720. return true;
  46721. }
  46722. if (this._albedoTexture === texture) {
  46723. return true;
  46724. }
  46725. if (this._ambientTexture === texture) {
  46726. return true;
  46727. }
  46728. if (this._opacityTexture === texture) {
  46729. return true;
  46730. }
  46731. if (this._reflectionTexture === texture) {
  46732. return true;
  46733. }
  46734. if (this._reflectivityTexture === texture) {
  46735. return true;
  46736. }
  46737. if (this._metallicTexture === texture) {
  46738. return true;
  46739. }
  46740. if (this._microSurfaceTexture === texture) {
  46741. return true;
  46742. }
  46743. if (this._bumpTexture === texture) {
  46744. return true;
  46745. }
  46746. if (this._lightmapTexture === texture) {
  46747. return true;
  46748. }
  46749. if (this._refractionTexture === texture) {
  46750. return true;
  46751. }
  46752. return false;
  46753. };
  46754. /**
  46755. * Makes a duplicate of the current material.
  46756. * @param name - name to use for the new material.
  46757. */
  46758. PBRMaterial.prototype.clone = function (name) {
  46759. var _this = this;
  46760. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46761. clone.id = name;
  46762. clone.name = name;
  46763. return clone;
  46764. };
  46765. /**
  46766. * Serializes this PBR Material.
  46767. * @returns - An object with the serialized material.
  46768. */
  46769. PBRMaterial.prototype.serialize = function () {
  46770. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46771. serializationObject.customType = "BABYLON.PBRMaterial";
  46772. return serializationObject;
  46773. };
  46774. // Statics
  46775. /**
  46776. * Parses a PBR Material from a serialized object.
  46777. * @param source - Serialized object.
  46778. * @param scene - BJS scene instance.
  46779. * @param rootUrl - url for the scene object
  46780. * @returns - PBRMaterial
  46781. */
  46782. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46783. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46784. };
  46785. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46786. /**
  46787. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46788. */
  46789. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46790. /**
  46791. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46792. */
  46793. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46794. /**
  46795. * 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.
  46796. * They are also discarded below the alpha cutoff threshold to improve performances.
  46797. */
  46798. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46799. __decorate([
  46800. BABYLON.serialize(),
  46801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46802. ], PBRMaterial.prototype, "directIntensity", void 0);
  46803. __decorate([
  46804. BABYLON.serialize(),
  46805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46806. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46807. __decorate([
  46808. BABYLON.serialize(),
  46809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46810. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46811. __decorate([
  46812. BABYLON.serialize(),
  46813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46814. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46815. __decorate([
  46816. BABYLON.serialize(),
  46817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46818. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46819. __decorate([
  46820. BABYLON.serializeAsTexture(),
  46821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46822. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46823. __decorate([
  46824. BABYLON.serializeAsTexture(),
  46825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46826. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46827. __decorate([
  46828. BABYLON.serialize(),
  46829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46830. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46831. __decorate([
  46832. BABYLON.serializeAsTexture(),
  46833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46834. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46835. __decorate([
  46836. BABYLON.serializeAsTexture(),
  46837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46838. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46839. __decorate([
  46840. BABYLON.serializeAsTexture(),
  46841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46842. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46843. __decorate([
  46844. BABYLON.serializeAsTexture(),
  46845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46846. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46847. __decorate([
  46848. BABYLON.serializeAsTexture(),
  46849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46850. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46851. __decorate([
  46852. BABYLON.serialize(),
  46853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46854. ], PBRMaterial.prototype, "metallic", void 0);
  46855. __decorate([
  46856. BABYLON.serialize(),
  46857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46858. ], PBRMaterial.prototype, "roughness", void 0);
  46859. __decorate([
  46860. BABYLON.serializeAsTexture(),
  46861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46862. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46863. __decorate([
  46864. BABYLON.serializeAsTexture(),
  46865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46866. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46867. __decorate([
  46868. BABYLON.serializeAsTexture(),
  46869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46870. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46871. __decorate([
  46872. BABYLON.serializeAsTexture(),
  46873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46874. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46875. __decorate([
  46876. BABYLON.serializeAsColor3("ambient"),
  46877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46878. ], PBRMaterial.prototype, "ambientColor", void 0);
  46879. __decorate([
  46880. BABYLON.serializeAsColor3("albedo"),
  46881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46882. ], PBRMaterial.prototype, "albedoColor", void 0);
  46883. __decorate([
  46884. BABYLON.serializeAsColor3("reflectivity"),
  46885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46886. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46887. __decorate([
  46888. BABYLON.serializeAsColor3("reflection"),
  46889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46890. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46891. __decorate([
  46892. BABYLON.serializeAsColor3("emissive"),
  46893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46894. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46895. __decorate([
  46896. BABYLON.serialize(),
  46897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46898. ], PBRMaterial.prototype, "microSurface", void 0);
  46899. __decorate([
  46900. BABYLON.serialize(),
  46901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46902. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46903. __decorate([
  46904. BABYLON.serialize(),
  46905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46906. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46907. __decorate([
  46908. BABYLON.serialize(),
  46909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46910. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46911. __decorate([
  46912. BABYLON.serialize(),
  46913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46914. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46915. __decorate([
  46916. BABYLON.serialize(),
  46917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46918. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46919. __decorate([
  46920. BABYLON.serialize(),
  46921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46922. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46923. __decorate([
  46924. BABYLON.serialize(),
  46925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46926. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46927. __decorate([
  46928. BABYLON.serialize(),
  46929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46930. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46931. __decorate([
  46932. BABYLON.serialize(),
  46933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46934. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46935. __decorate([
  46936. BABYLON.serialize(),
  46937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46938. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46939. __decorate([
  46940. BABYLON.serialize(),
  46941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46942. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46943. __decorate([
  46944. BABYLON.serialize(),
  46945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46946. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46947. __decorate([
  46948. BABYLON.serialize(),
  46949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46950. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46951. __decorate([
  46952. BABYLON.serialize(),
  46953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46954. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46955. __decorate([
  46956. BABYLON.serialize(),
  46957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46958. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46959. __decorate([
  46960. BABYLON.serialize(),
  46961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46962. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46963. __decorate([
  46964. BABYLON.serialize(),
  46965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46966. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46967. __decorate([
  46968. BABYLON.serialize(),
  46969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46970. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46971. __decorate([
  46972. BABYLON.serialize(),
  46973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46974. ], PBRMaterial.prototype, "useParallax", void 0);
  46975. __decorate([
  46976. BABYLON.serialize(),
  46977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46978. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46979. __decorate([
  46980. BABYLON.serialize(),
  46981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46982. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46983. __decorate([
  46984. BABYLON.serialize(),
  46985. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46986. ], PBRMaterial.prototype, "disableLighting", void 0);
  46987. __decorate([
  46988. BABYLON.serialize(),
  46989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46990. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46991. __decorate([
  46992. BABYLON.serialize(),
  46993. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46994. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46995. __decorate([
  46996. BABYLON.serialize(),
  46997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46998. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46999. __decorate([
  47000. BABYLON.serialize(),
  47001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47002. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47003. __decorate([
  47004. BABYLON.serialize(),
  47005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47006. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47007. __decorate([
  47008. BABYLON.serialize(),
  47009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47010. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47011. __decorate([
  47012. BABYLON.serialize(),
  47013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47014. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47015. __decorate([
  47016. BABYLON.serializeAsTexture(),
  47017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47018. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47019. __decorate([
  47020. BABYLON.serialize(),
  47021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47022. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47023. __decorate([
  47024. BABYLON.serialize(),
  47025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47026. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47027. __decorate([
  47028. BABYLON.serialize(),
  47029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47030. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47031. __decorate([
  47032. BABYLON.serialize(),
  47033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47034. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47035. __decorate([
  47036. BABYLON.serialize(),
  47037. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47038. ], PBRMaterial.prototype, "unlit", void 0);
  47039. return PBRMaterial;
  47040. }(BABYLON.PBRBaseMaterial));
  47041. BABYLON.PBRMaterial = PBRMaterial;
  47042. })(BABYLON || (BABYLON = {}));
  47043. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47044. var BABYLON;
  47045. (function (BABYLON) {
  47046. /**
  47047. * The PBR material of BJS following the metal roughness convention.
  47048. *
  47049. * This fits to the PBR convention in the GLTF definition:
  47050. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47051. */
  47052. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47053. __extends(PBRMetallicRoughnessMaterial, _super);
  47054. /**
  47055. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47056. *
  47057. * @param name The material name
  47058. * @param scene The scene the material will be use in.
  47059. */
  47060. function PBRMetallicRoughnessMaterial(name, scene) {
  47061. var _this = _super.call(this, name, scene) || this;
  47062. _this._useRoughnessFromMetallicTextureAlpha = false;
  47063. _this._useRoughnessFromMetallicTextureGreen = true;
  47064. _this._useMetallnessFromMetallicTextureBlue = true;
  47065. _this.metallic = 1.0;
  47066. _this.roughness = 1.0;
  47067. return _this;
  47068. }
  47069. /**
  47070. * Return the currrent class name of the material.
  47071. */
  47072. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47073. return "PBRMetallicRoughnessMaterial";
  47074. };
  47075. /**
  47076. * Return the active textures of the material.
  47077. */
  47078. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47079. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47080. if (this.baseTexture) {
  47081. activeTextures.push(this.baseTexture);
  47082. }
  47083. if (this.metallicRoughnessTexture) {
  47084. activeTextures.push(this.metallicRoughnessTexture);
  47085. }
  47086. return activeTextures;
  47087. };
  47088. /**
  47089. * Checks to see if a texture is used in the material.
  47090. * @param texture - Base texture to use.
  47091. * @returns - Boolean specifying if a texture is used in the material.
  47092. */
  47093. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47094. if (_super.prototype.hasTexture.call(this, texture)) {
  47095. return true;
  47096. }
  47097. if (this.baseTexture === texture) {
  47098. return true;
  47099. }
  47100. if (this.metallicRoughnessTexture === texture) {
  47101. return true;
  47102. }
  47103. return false;
  47104. };
  47105. /**
  47106. * Makes a duplicate of the current material.
  47107. * @param name - name to use for the new material.
  47108. */
  47109. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47110. var _this = this;
  47111. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47112. clone.id = name;
  47113. clone.name = name;
  47114. return clone;
  47115. };
  47116. /**
  47117. * Serialize the material to a parsable JSON object.
  47118. */
  47119. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47120. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47121. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47122. return serializationObject;
  47123. };
  47124. /**
  47125. * Parses a JSON object correponding to the serialize function.
  47126. */
  47127. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47128. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47129. };
  47130. __decorate([
  47131. BABYLON.serializeAsColor3(),
  47132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47133. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47134. __decorate([
  47135. BABYLON.serializeAsTexture(),
  47136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47137. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47138. __decorate([
  47139. BABYLON.serialize(),
  47140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47141. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47142. __decorate([
  47143. BABYLON.serialize(),
  47144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47145. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47146. __decorate([
  47147. BABYLON.serializeAsTexture(),
  47148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47149. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47150. return PBRMetallicRoughnessMaterial;
  47151. }(BABYLON.PBRBaseSimpleMaterial));
  47152. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47153. })(BABYLON || (BABYLON = {}));
  47154. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47155. var BABYLON;
  47156. (function (BABYLON) {
  47157. /**
  47158. * The PBR material of BJS following the specular glossiness convention.
  47159. *
  47160. * This fits to the PBR convention in the GLTF definition:
  47161. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47162. */
  47163. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47164. __extends(PBRSpecularGlossinessMaterial, _super);
  47165. /**
  47166. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47167. *
  47168. * @param name The material name
  47169. * @param scene The scene the material will be use in.
  47170. */
  47171. function PBRSpecularGlossinessMaterial(name, scene) {
  47172. var _this = _super.call(this, name, scene) || this;
  47173. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47174. return _this;
  47175. }
  47176. /**
  47177. * Return the currrent class name of the material.
  47178. */
  47179. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47180. return "PBRSpecularGlossinessMaterial";
  47181. };
  47182. /**
  47183. * Return the active textures of the material.
  47184. */
  47185. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47186. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47187. if (this.diffuseTexture) {
  47188. activeTextures.push(this.diffuseTexture);
  47189. }
  47190. if (this.specularGlossinessTexture) {
  47191. activeTextures.push(this.specularGlossinessTexture);
  47192. }
  47193. return activeTextures;
  47194. };
  47195. /**
  47196. * Checks to see if a texture is used in the material.
  47197. * @param texture - Base texture to use.
  47198. * @returns - Boolean specifying if a texture is used in the material.
  47199. */
  47200. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47201. if (_super.prototype.hasTexture.call(this, texture)) {
  47202. return true;
  47203. }
  47204. if (this.diffuseTexture === texture) {
  47205. return true;
  47206. }
  47207. if (this.specularGlossinessTexture === texture) {
  47208. return true;
  47209. }
  47210. return false;
  47211. };
  47212. /**
  47213. * Makes a duplicate of the current material.
  47214. * @param name - name to use for the new material.
  47215. */
  47216. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47217. var _this = this;
  47218. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47219. clone.id = name;
  47220. clone.name = name;
  47221. return clone;
  47222. };
  47223. /**
  47224. * Serialize the material to a parsable JSON object.
  47225. */
  47226. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47227. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47228. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47229. return serializationObject;
  47230. };
  47231. /**
  47232. * Parses a JSON object correponding to the serialize function.
  47233. */
  47234. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47235. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47236. };
  47237. __decorate([
  47238. BABYLON.serializeAsColor3("diffuse"),
  47239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47240. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47241. __decorate([
  47242. BABYLON.serializeAsTexture(),
  47243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47244. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47245. __decorate([
  47246. BABYLON.serializeAsColor3("specular"),
  47247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47248. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47249. __decorate([
  47250. BABYLON.serialize(),
  47251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47252. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47253. __decorate([
  47254. BABYLON.serializeAsTexture(),
  47255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47256. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47257. return PBRSpecularGlossinessMaterial;
  47258. }(BABYLON.PBRBaseSimpleMaterial));
  47259. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47260. })(BABYLON || (BABYLON = {}));
  47261. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47262. var BABYLON;
  47263. (function (BABYLON) {
  47264. BABYLON.CameraInputTypes = {};
  47265. var CameraInputsManager = /** @class */ (function () {
  47266. function CameraInputsManager(camera) {
  47267. this.attached = {};
  47268. this.camera = camera;
  47269. this.checkInputs = function () { };
  47270. }
  47271. /**
  47272. * Add an input method to a camera.
  47273. * builtin inputs example: camera.inputs.addGamepad();
  47274. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47275. * @param input camera input method
  47276. */
  47277. CameraInputsManager.prototype.add = function (input) {
  47278. var type = input.getSimpleName();
  47279. if (this.attached[type]) {
  47280. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47281. return;
  47282. }
  47283. this.attached[type] = input;
  47284. input.camera = this.camera;
  47285. //for checkInputs, we are dynamically creating a function
  47286. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47287. if (input.checkInputs) {
  47288. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47289. }
  47290. if (this.attachedElement) {
  47291. input.attachControl(this.attachedElement);
  47292. }
  47293. };
  47294. /**
  47295. * Remove a specific input method from a camera
  47296. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47297. * @param inputToRemove camera input method
  47298. */
  47299. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47300. for (var cam in this.attached) {
  47301. var input = this.attached[cam];
  47302. if (input === inputToRemove) {
  47303. input.detachControl(this.attachedElement);
  47304. input.camera = null;
  47305. delete this.attached[cam];
  47306. this.rebuildInputCheck();
  47307. }
  47308. }
  47309. };
  47310. CameraInputsManager.prototype.removeByType = function (inputType) {
  47311. for (var cam in this.attached) {
  47312. var input = this.attached[cam];
  47313. if (input.getClassName() === inputType) {
  47314. input.detachControl(this.attachedElement);
  47315. input.camera = null;
  47316. delete this.attached[cam];
  47317. this.rebuildInputCheck();
  47318. }
  47319. }
  47320. };
  47321. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47322. var current = this.checkInputs;
  47323. return function () {
  47324. current();
  47325. fn();
  47326. };
  47327. };
  47328. CameraInputsManager.prototype.attachInput = function (input) {
  47329. if (this.attachedElement) {
  47330. input.attachControl(this.attachedElement, this.noPreventDefault);
  47331. }
  47332. };
  47333. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47334. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47335. if (this.attachedElement) {
  47336. return;
  47337. }
  47338. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47339. this.attachedElement = element;
  47340. this.noPreventDefault = noPreventDefault;
  47341. for (var cam in this.attached) {
  47342. this.attached[cam].attachControl(element, noPreventDefault);
  47343. }
  47344. };
  47345. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47346. if (disconnect === void 0) { disconnect = false; }
  47347. if (this.attachedElement !== element) {
  47348. return;
  47349. }
  47350. for (var cam in this.attached) {
  47351. this.attached[cam].detachControl(element);
  47352. if (disconnect) {
  47353. this.attached[cam].camera = null;
  47354. }
  47355. }
  47356. this.attachedElement = null;
  47357. };
  47358. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47359. this.checkInputs = function () { };
  47360. for (var cam in this.attached) {
  47361. var input = this.attached[cam];
  47362. if (input.checkInputs) {
  47363. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47364. }
  47365. }
  47366. };
  47367. /**
  47368. * Remove all attached input methods from a camera
  47369. */
  47370. CameraInputsManager.prototype.clear = function () {
  47371. if (this.attachedElement) {
  47372. this.detachElement(this.attachedElement, true);
  47373. }
  47374. this.attached = {};
  47375. this.attachedElement = null;
  47376. this.checkInputs = function () { };
  47377. };
  47378. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47379. var inputs = {};
  47380. for (var cam in this.attached) {
  47381. var input = this.attached[cam];
  47382. var res = BABYLON.SerializationHelper.Serialize(input);
  47383. inputs[input.getClassName()] = res;
  47384. }
  47385. serializedCamera.inputsmgr = inputs;
  47386. };
  47387. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47388. var parsedInputs = parsedCamera.inputsmgr;
  47389. if (parsedInputs) {
  47390. this.clear();
  47391. for (var n in parsedInputs) {
  47392. var construct = BABYLON.CameraInputTypes[n];
  47393. if (construct) {
  47394. var parsedinput = parsedInputs[n];
  47395. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47396. this.add(input);
  47397. }
  47398. }
  47399. }
  47400. else {
  47401. //2016-03-08 this part is for managing backward compatibility
  47402. for (var n in this.attached) {
  47403. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47404. if (construct) {
  47405. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47406. this.remove(this.attached[n]);
  47407. this.add(input);
  47408. }
  47409. }
  47410. }
  47411. };
  47412. return CameraInputsManager;
  47413. }());
  47414. BABYLON.CameraInputsManager = CameraInputsManager;
  47415. })(BABYLON || (BABYLON = {}));
  47416. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47417. var BABYLON;
  47418. (function (BABYLON) {
  47419. var TargetCamera = /** @class */ (function (_super) {
  47420. __extends(TargetCamera, _super);
  47421. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47422. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47423. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47424. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47425. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47426. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47427. _this.speed = 2.0;
  47428. _this.noRotationConstraint = false;
  47429. _this.lockedTarget = null;
  47430. _this._currentTarget = BABYLON.Vector3.Zero();
  47431. _this._viewMatrix = BABYLON.Matrix.Zero();
  47432. _this._camMatrix = BABYLON.Matrix.Zero();
  47433. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47434. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47435. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47436. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47437. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47438. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47439. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47440. return _this;
  47441. }
  47442. TargetCamera.prototype.getFrontPosition = function (distance) {
  47443. this.getWorldMatrix();
  47444. var direction = this.getTarget().subtract(this.position);
  47445. direction.normalize();
  47446. direction.scaleInPlace(distance);
  47447. return this.globalPosition.add(direction);
  47448. };
  47449. TargetCamera.prototype._getLockedTargetPosition = function () {
  47450. if (!this.lockedTarget) {
  47451. return null;
  47452. }
  47453. if (this.lockedTarget.absolutePosition) {
  47454. this.lockedTarget.computeWorldMatrix();
  47455. }
  47456. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47457. };
  47458. TargetCamera.prototype.storeState = function () {
  47459. this._storedPosition = this.position.clone();
  47460. this._storedRotation = this.rotation.clone();
  47461. if (this.rotationQuaternion) {
  47462. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47463. }
  47464. return _super.prototype.storeState.call(this);
  47465. };
  47466. /**
  47467. * Restored camera state. You must call storeState() first
  47468. */
  47469. TargetCamera.prototype._restoreStateValues = function () {
  47470. if (!_super.prototype._restoreStateValues.call(this)) {
  47471. return false;
  47472. }
  47473. this.position = this._storedPosition.clone();
  47474. this.rotation = this._storedRotation.clone();
  47475. if (this.rotationQuaternion) {
  47476. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47477. }
  47478. this.cameraDirection.copyFromFloats(0, 0, 0);
  47479. this.cameraRotation.copyFromFloats(0, 0);
  47480. return true;
  47481. };
  47482. // Cache
  47483. TargetCamera.prototype._initCache = function () {
  47484. _super.prototype._initCache.call(this);
  47485. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47486. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47487. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47488. };
  47489. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47490. if (!ignoreParentClass) {
  47491. _super.prototype._updateCache.call(this);
  47492. }
  47493. var lockedTargetPosition = this._getLockedTargetPosition();
  47494. if (!lockedTargetPosition) {
  47495. this._cache.lockedTarget = null;
  47496. }
  47497. else {
  47498. if (!this._cache.lockedTarget) {
  47499. this._cache.lockedTarget = lockedTargetPosition.clone();
  47500. }
  47501. else {
  47502. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47503. }
  47504. }
  47505. this._cache.rotation.copyFrom(this.rotation);
  47506. if (this.rotationQuaternion)
  47507. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47508. };
  47509. // Synchronized
  47510. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47511. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47512. return false;
  47513. }
  47514. var lockedTargetPosition = this._getLockedTargetPosition();
  47515. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47516. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47517. };
  47518. // Methods
  47519. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47520. var engine = this.getEngine();
  47521. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47522. };
  47523. // Target
  47524. TargetCamera.prototype.setTarget = function (target) {
  47525. this.upVector.normalize();
  47526. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47527. this._camMatrix.invert();
  47528. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47529. var vDir = target.subtract(this.position);
  47530. if (vDir.x >= 0.0) {
  47531. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47532. }
  47533. else {
  47534. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47535. }
  47536. this.rotation.z = 0;
  47537. if (isNaN(this.rotation.x)) {
  47538. this.rotation.x = 0;
  47539. }
  47540. if (isNaN(this.rotation.y)) {
  47541. this.rotation.y = 0;
  47542. }
  47543. if (isNaN(this.rotation.z)) {
  47544. this.rotation.z = 0;
  47545. }
  47546. if (this.rotationQuaternion) {
  47547. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47548. }
  47549. };
  47550. /**
  47551. * Return the current target position of the camera. This value is expressed in local space.
  47552. */
  47553. TargetCamera.prototype.getTarget = function () {
  47554. return this._currentTarget;
  47555. };
  47556. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47557. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47558. };
  47559. TargetCamera.prototype._updatePosition = function () {
  47560. if (this.parent) {
  47561. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47562. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47563. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47564. return;
  47565. }
  47566. this.position.addInPlace(this.cameraDirection);
  47567. };
  47568. TargetCamera.prototype._checkInputs = function () {
  47569. var needToMove = this._decideIfNeedsToMove();
  47570. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47571. // Move
  47572. if (needToMove) {
  47573. this._updatePosition();
  47574. }
  47575. // Rotate
  47576. if (needToRotate) {
  47577. this.rotation.x += this.cameraRotation.x;
  47578. this.rotation.y += this.cameraRotation.y;
  47579. //rotate, if quaternion is set and rotation was used
  47580. if (this.rotationQuaternion) {
  47581. var len = this.rotation.lengthSquared();
  47582. if (len) {
  47583. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47584. }
  47585. }
  47586. if (!this.noRotationConstraint) {
  47587. var limit = (Math.PI / 2) * 0.95;
  47588. if (this.rotation.x > limit)
  47589. this.rotation.x = limit;
  47590. if (this.rotation.x < -limit)
  47591. this.rotation.x = -limit;
  47592. }
  47593. }
  47594. // Inertia
  47595. if (needToMove) {
  47596. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47597. this.cameraDirection.x = 0;
  47598. }
  47599. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47600. this.cameraDirection.y = 0;
  47601. }
  47602. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47603. this.cameraDirection.z = 0;
  47604. }
  47605. this.cameraDirection.scaleInPlace(this.inertia);
  47606. }
  47607. if (needToRotate) {
  47608. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47609. this.cameraRotation.x = 0;
  47610. }
  47611. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47612. this.cameraRotation.y = 0;
  47613. }
  47614. this.cameraRotation.scaleInPlace(this.inertia);
  47615. }
  47616. _super.prototype._checkInputs.call(this);
  47617. };
  47618. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47619. if (this.rotationQuaternion) {
  47620. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47621. }
  47622. else {
  47623. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47624. }
  47625. //update the up vector!
  47626. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47627. };
  47628. TargetCamera.prototype._getViewMatrix = function () {
  47629. if (this.lockedTarget) {
  47630. this.setTarget(this._getLockedTargetPosition());
  47631. }
  47632. // Compute
  47633. this._updateCameraRotationMatrix();
  47634. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47635. // Computing target and final matrix
  47636. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47637. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47638. return this._viewMatrix;
  47639. };
  47640. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47641. if (this.parent) {
  47642. var parentWorldMatrix = this.parent.getWorldMatrix();
  47643. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47644. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47645. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47646. this._markSyncedWithParent();
  47647. }
  47648. else {
  47649. this._globalPosition.copyFrom(this.position);
  47650. this._globalCurrentTarget.copyFrom(target);
  47651. this._globalCurrentUpVector.copyFrom(up);
  47652. }
  47653. if (this.getScene().useRightHandedSystem) {
  47654. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47655. }
  47656. else {
  47657. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47658. }
  47659. };
  47660. /**
  47661. * @override
  47662. * Override Camera.createRigCamera
  47663. */
  47664. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47665. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47666. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47667. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47668. if (!this.rotationQuaternion) {
  47669. this.rotationQuaternion = new BABYLON.Quaternion();
  47670. }
  47671. rigCamera._cameraRigParams = {};
  47672. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47673. }
  47674. return rigCamera;
  47675. }
  47676. return null;
  47677. };
  47678. /**
  47679. * @override
  47680. * Override Camera._updateRigCameras
  47681. */
  47682. TargetCamera.prototype._updateRigCameras = function () {
  47683. var camLeft = this._rigCameras[0];
  47684. var camRight = this._rigCameras[1];
  47685. switch (this.cameraRigMode) {
  47686. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47690. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47691. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47692. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47693. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47694. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47695. camLeft.setTarget(this.getTarget());
  47696. camRight.setTarget(this.getTarget());
  47697. break;
  47698. case BABYLON.Camera.RIG_MODE_VR:
  47699. if (camLeft.rotationQuaternion) {
  47700. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47701. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47702. }
  47703. else {
  47704. camLeft.rotation.copyFrom(this.rotation);
  47705. camRight.rotation.copyFrom(this.rotation);
  47706. }
  47707. camLeft.position.copyFrom(this.position);
  47708. camRight.position.copyFrom(this.position);
  47709. break;
  47710. }
  47711. _super.prototype._updateRigCameras.call(this);
  47712. };
  47713. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47714. if (!this._rigCamTransformMatrix) {
  47715. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47716. }
  47717. var target = this.getTarget();
  47718. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47719. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47720. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47721. };
  47722. TargetCamera.prototype.getClassName = function () {
  47723. return "TargetCamera";
  47724. };
  47725. __decorate([
  47726. BABYLON.serializeAsVector3()
  47727. ], TargetCamera.prototype, "rotation", void 0);
  47728. __decorate([
  47729. BABYLON.serialize()
  47730. ], TargetCamera.prototype, "speed", void 0);
  47731. __decorate([
  47732. BABYLON.serializeAsMeshReference("lockedTargetId")
  47733. ], TargetCamera.prototype, "lockedTarget", void 0);
  47734. return TargetCamera;
  47735. }(BABYLON.Camera));
  47736. BABYLON.TargetCamera = TargetCamera;
  47737. })(BABYLON || (BABYLON = {}));
  47738. //# sourceMappingURL=babylon.targetCamera.js.map
  47739. var BABYLON;
  47740. (function (BABYLON) {
  47741. var FreeCameraMouseInput = /** @class */ (function () {
  47742. function FreeCameraMouseInput(touchEnabled) {
  47743. if (touchEnabled === void 0) { touchEnabled = true; }
  47744. this.touchEnabled = touchEnabled;
  47745. this.buttons = [0, 1, 2];
  47746. this.angularSensibility = 2000.0;
  47747. this.previousPosition = null;
  47748. }
  47749. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47750. var _this = this;
  47751. var engine = this.camera.getEngine();
  47752. if (!this._pointerInput) {
  47753. this._pointerInput = function (p, s) {
  47754. var evt = p.event;
  47755. if (engine.isInVRExclusivePointerMode) {
  47756. return;
  47757. }
  47758. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47759. return;
  47760. }
  47761. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47762. return;
  47763. }
  47764. var srcElement = (evt.srcElement || evt.target);
  47765. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47766. try {
  47767. srcElement.setPointerCapture(evt.pointerId);
  47768. }
  47769. catch (e) {
  47770. //Nothing to do with the error. Execution will continue.
  47771. }
  47772. _this.previousPosition = {
  47773. x: evt.clientX,
  47774. y: evt.clientY
  47775. };
  47776. if (!noPreventDefault) {
  47777. evt.preventDefault();
  47778. element.focus();
  47779. }
  47780. }
  47781. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47782. try {
  47783. srcElement.releasePointerCapture(evt.pointerId);
  47784. }
  47785. catch (e) {
  47786. //Nothing to do with the error.
  47787. }
  47788. _this.previousPosition = null;
  47789. if (!noPreventDefault) {
  47790. evt.preventDefault();
  47791. }
  47792. }
  47793. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47794. if (!_this.previousPosition || engine.isPointerLock) {
  47795. return;
  47796. }
  47797. var offsetX = evt.clientX - _this.previousPosition.x;
  47798. if (_this.camera.getScene().useRightHandedSystem)
  47799. offsetX *= -1;
  47800. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47801. offsetX *= -1;
  47802. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47803. var offsetY = evt.clientY - _this.previousPosition.y;
  47804. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47805. _this.previousPosition = {
  47806. x: evt.clientX,
  47807. y: evt.clientY
  47808. };
  47809. if (!noPreventDefault) {
  47810. evt.preventDefault();
  47811. }
  47812. }
  47813. };
  47814. }
  47815. this._onMouseMove = function (evt) {
  47816. if (!engine.isPointerLock) {
  47817. return;
  47818. }
  47819. if (engine.isInVRExclusivePointerMode) {
  47820. return;
  47821. }
  47822. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47823. if (_this.camera.getScene().useRightHandedSystem)
  47824. offsetX *= -1;
  47825. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47826. offsetX *= -1;
  47827. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47828. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47829. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47830. _this.previousPosition = null;
  47831. if (!noPreventDefault) {
  47832. evt.preventDefault();
  47833. }
  47834. };
  47835. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47836. element.addEventListener("mousemove", this._onMouseMove, false);
  47837. };
  47838. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47839. if (this._observer && element) {
  47840. this.camera.getScene().onPointerObservable.remove(this._observer);
  47841. if (this._onMouseMove) {
  47842. element.removeEventListener("mousemove", this._onMouseMove);
  47843. }
  47844. this._observer = null;
  47845. this._onMouseMove = null;
  47846. this.previousPosition = null;
  47847. }
  47848. };
  47849. FreeCameraMouseInput.prototype.getClassName = function () {
  47850. return "FreeCameraMouseInput";
  47851. };
  47852. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47853. return "mouse";
  47854. };
  47855. __decorate([
  47856. BABYLON.serialize()
  47857. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47858. __decorate([
  47859. BABYLON.serialize()
  47860. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47861. return FreeCameraMouseInput;
  47862. }());
  47863. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47864. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47865. })(BABYLON || (BABYLON = {}));
  47866. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47867. var BABYLON;
  47868. (function (BABYLON) {
  47869. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47870. function FreeCameraKeyboardMoveInput() {
  47871. this._keys = new Array();
  47872. this.keysUp = [38];
  47873. this.keysDown = [40];
  47874. this.keysLeft = [37];
  47875. this.keysRight = [39];
  47876. }
  47877. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47878. var _this = this;
  47879. if (this._onCanvasBlurObserver) {
  47880. return;
  47881. }
  47882. this._scene = this.camera.getScene();
  47883. this._engine = this._scene.getEngine();
  47884. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47885. _this._keys = [];
  47886. });
  47887. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47888. var evt = info.event;
  47889. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47890. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47891. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47892. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47893. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47894. var index = _this._keys.indexOf(evt.keyCode);
  47895. if (index === -1) {
  47896. _this._keys.push(evt.keyCode);
  47897. }
  47898. if (!noPreventDefault) {
  47899. evt.preventDefault();
  47900. }
  47901. }
  47902. }
  47903. else {
  47904. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47905. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47906. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47907. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47908. var index = _this._keys.indexOf(evt.keyCode);
  47909. if (index >= 0) {
  47910. _this._keys.splice(index, 1);
  47911. }
  47912. if (!noPreventDefault) {
  47913. evt.preventDefault();
  47914. }
  47915. }
  47916. }
  47917. });
  47918. };
  47919. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47920. if (this._scene) {
  47921. if (this._onKeyboardObserver) {
  47922. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47923. }
  47924. if (this._onCanvasBlurObserver) {
  47925. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47926. }
  47927. this._onKeyboardObserver = null;
  47928. this._onCanvasBlurObserver = null;
  47929. }
  47930. this._keys = [];
  47931. };
  47932. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47933. if (this._onKeyboardObserver) {
  47934. var camera = this.camera;
  47935. // Keyboard
  47936. for (var index = 0; index < this._keys.length; index++) {
  47937. var keyCode = this._keys[index];
  47938. var speed = camera._computeLocalCameraSpeed();
  47939. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47940. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47941. }
  47942. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47943. camera._localDirection.copyFromFloats(0, 0, speed);
  47944. }
  47945. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47946. camera._localDirection.copyFromFloats(speed, 0, 0);
  47947. }
  47948. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47949. camera._localDirection.copyFromFloats(0, 0, -speed);
  47950. }
  47951. if (camera.getScene().useRightHandedSystem) {
  47952. camera._localDirection.z *= -1;
  47953. }
  47954. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47955. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47956. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47957. }
  47958. }
  47959. };
  47960. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47961. return "FreeCameraKeyboardMoveInput";
  47962. };
  47963. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47964. this._keys = [];
  47965. };
  47966. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47967. return "keyboard";
  47968. };
  47969. __decorate([
  47970. BABYLON.serialize()
  47971. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47972. __decorate([
  47973. BABYLON.serialize()
  47974. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47975. __decorate([
  47976. BABYLON.serialize()
  47977. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47978. __decorate([
  47979. BABYLON.serialize()
  47980. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47981. return FreeCameraKeyboardMoveInput;
  47982. }());
  47983. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47984. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47985. })(BABYLON || (BABYLON = {}));
  47986. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47987. var BABYLON;
  47988. (function (BABYLON) {
  47989. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47990. __extends(FreeCameraInputsManager, _super);
  47991. function FreeCameraInputsManager(camera) {
  47992. return _super.call(this, camera) || this;
  47993. }
  47994. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47995. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47996. return this;
  47997. };
  47998. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47999. if (touchEnabled === void 0) { touchEnabled = true; }
  48000. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48001. return this;
  48002. };
  48003. FreeCameraInputsManager.prototype.addGamepad = function () {
  48004. this.add(new BABYLON.FreeCameraGamepadInput());
  48005. return this;
  48006. };
  48007. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48008. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48009. return this;
  48010. };
  48011. FreeCameraInputsManager.prototype.addTouch = function () {
  48012. this.add(new BABYLON.FreeCameraTouchInput());
  48013. return this;
  48014. };
  48015. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48016. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48017. return this;
  48018. };
  48019. return FreeCameraInputsManager;
  48020. }(BABYLON.CameraInputsManager));
  48021. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48022. })(BABYLON || (BABYLON = {}));
  48023. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48024. var BABYLON;
  48025. (function (BABYLON) {
  48026. var FreeCamera = /** @class */ (function (_super) {
  48027. __extends(FreeCamera, _super);
  48028. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48029. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48030. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48031. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48032. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48033. _this.checkCollisions = false;
  48034. _this.applyGravity = false;
  48035. _this._needMoveForGravity = false;
  48036. _this._oldPosition = BABYLON.Vector3.Zero();
  48037. _this._diffPosition = BABYLON.Vector3.Zero();
  48038. _this._newPosition = BABYLON.Vector3.Zero();
  48039. // Collisions
  48040. _this._collisionMask = -1;
  48041. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48042. if (collidedMesh === void 0) { collidedMesh = null; }
  48043. //TODO move this to the collision coordinator!
  48044. if (_this.getScene().workerCollisions)
  48045. newPosition.multiplyInPlace(_this._collider._radius);
  48046. var updatePosition = function (newPos) {
  48047. _this._newPosition.copyFrom(newPos);
  48048. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48049. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48050. _this.position.addInPlace(_this._diffPosition);
  48051. if (_this.onCollide && collidedMesh) {
  48052. _this.onCollide(collidedMesh);
  48053. }
  48054. }
  48055. };
  48056. updatePosition(newPosition);
  48057. };
  48058. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48059. _this.inputs.addKeyboard().addMouse();
  48060. return _this;
  48061. }
  48062. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48063. //-- begin properties for backward compatibility for inputs
  48064. /**
  48065. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48066. * Higher values reduce sensitivity.
  48067. */
  48068. get: function () {
  48069. var mouse = this.inputs.attached["mouse"];
  48070. if (mouse)
  48071. return mouse.angularSensibility;
  48072. return 0;
  48073. },
  48074. /**
  48075. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48076. * Higher values reduce sensitivity.
  48077. */
  48078. set: function (value) {
  48079. var mouse = this.inputs.attached["mouse"];
  48080. if (mouse)
  48081. mouse.angularSensibility = value;
  48082. },
  48083. enumerable: true,
  48084. configurable: true
  48085. });
  48086. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48087. get: function () {
  48088. var keyboard = this.inputs.attached["keyboard"];
  48089. if (keyboard)
  48090. return keyboard.keysUp;
  48091. return [];
  48092. },
  48093. set: function (value) {
  48094. var keyboard = this.inputs.attached["keyboard"];
  48095. if (keyboard)
  48096. keyboard.keysUp = value;
  48097. },
  48098. enumerable: true,
  48099. configurable: true
  48100. });
  48101. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48102. get: function () {
  48103. var keyboard = this.inputs.attached["keyboard"];
  48104. if (keyboard)
  48105. return keyboard.keysDown;
  48106. return [];
  48107. },
  48108. set: function (value) {
  48109. var keyboard = this.inputs.attached["keyboard"];
  48110. if (keyboard)
  48111. keyboard.keysDown = value;
  48112. },
  48113. enumerable: true,
  48114. configurable: true
  48115. });
  48116. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48117. get: function () {
  48118. var keyboard = this.inputs.attached["keyboard"];
  48119. if (keyboard)
  48120. return keyboard.keysLeft;
  48121. return [];
  48122. },
  48123. set: function (value) {
  48124. var keyboard = this.inputs.attached["keyboard"];
  48125. if (keyboard)
  48126. keyboard.keysLeft = value;
  48127. },
  48128. enumerable: true,
  48129. configurable: true
  48130. });
  48131. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48132. get: function () {
  48133. var keyboard = this.inputs.attached["keyboard"];
  48134. if (keyboard)
  48135. return keyboard.keysRight;
  48136. return [];
  48137. },
  48138. set: function (value) {
  48139. var keyboard = this.inputs.attached["keyboard"];
  48140. if (keyboard)
  48141. keyboard.keysRight = value;
  48142. },
  48143. enumerable: true,
  48144. configurable: true
  48145. });
  48146. // Controls
  48147. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48148. this.inputs.attachElement(element, noPreventDefault);
  48149. };
  48150. FreeCamera.prototype.detachControl = function (element) {
  48151. this.inputs.detachElement(element);
  48152. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48153. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48154. };
  48155. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48156. get: function () {
  48157. return this._collisionMask;
  48158. },
  48159. set: function (mask) {
  48160. this._collisionMask = !isNaN(mask) ? mask : -1;
  48161. },
  48162. enumerable: true,
  48163. configurable: true
  48164. });
  48165. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48166. var globalPosition;
  48167. if (this.parent) {
  48168. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48169. }
  48170. else {
  48171. globalPosition = this.position;
  48172. }
  48173. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48174. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48175. if (!this._collider) {
  48176. this._collider = new BABYLON.Collider();
  48177. }
  48178. this._collider._radius = this.ellipsoid;
  48179. this._collider.collisionMask = this._collisionMask;
  48180. //no need for clone, as long as gravity is not on.
  48181. var actualDisplacement = displacement;
  48182. //add gravity to the direction to prevent the dual-collision checking
  48183. if (this.applyGravity) {
  48184. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48185. actualDisplacement = displacement.add(this.getScene().gravity);
  48186. }
  48187. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48188. };
  48189. FreeCamera.prototype._checkInputs = function () {
  48190. if (!this._localDirection) {
  48191. this._localDirection = BABYLON.Vector3.Zero();
  48192. this._transformedDirection = BABYLON.Vector3.Zero();
  48193. }
  48194. this.inputs.checkInputs();
  48195. _super.prototype._checkInputs.call(this);
  48196. };
  48197. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48198. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48199. };
  48200. FreeCamera.prototype._updatePosition = function () {
  48201. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48202. this._collideWithWorld(this.cameraDirection);
  48203. }
  48204. else {
  48205. _super.prototype._updatePosition.call(this);
  48206. }
  48207. };
  48208. FreeCamera.prototype.dispose = function () {
  48209. this.inputs.clear();
  48210. _super.prototype.dispose.call(this);
  48211. };
  48212. FreeCamera.prototype.getClassName = function () {
  48213. return "FreeCamera";
  48214. };
  48215. __decorate([
  48216. BABYLON.serializeAsVector3()
  48217. ], FreeCamera.prototype, "ellipsoid", void 0);
  48218. __decorate([
  48219. BABYLON.serializeAsVector3()
  48220. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48221. __decorate([
  48222. BABYLON.serialize()
  48223. ], FreeCamera.prototype, "checkCollisions", void 0);
  48224. __decorate([
  48225. BABYLON.serialize()
  48226. ], FreeCamera.prototype, "applyGravity", void 0);
  48227. return FreeCamera;
  48228. }(BABYLON.TargetCamera));
  48229. BABYLON.FreeCamera = FreeCamera;
  48230. })(BABYLON || (BABYLON = {}));
  48231. //# sourceMappingURL=babylon.freeCamera.js.map
  48232. var BABYLON;
  48233. (function (BABYLON) {
  48234. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48235. function ArcRotateCameraKeyboardMoveInput() {
  48236. this._keys = new Array();
  48237. this.keysUp = [38];
  48238. this.keysDown = [40];
  48239. this.keysLeft = [37];
  48240. this.keysRight = [39];
  48241. this.keysReset = [220];
  48242. this.panningSensibility = 50.0;
  48243. this.zoomingSensibility = 25.0;
  48244. this.useAltToZoom = true;
  48245. }
  48246. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48247. var _this = this;
  48248. if (this._onCanvasBlurObserver) {
  48249. return;
  48250. }
  48251. this._scene = this.camera.getScene();
  48252. this._engine = this._scene.getEngine();
  48253. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48254. _this._keys = [];
  48255. });
  48256. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48257. var evt = info.event;
  48258. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48259. _this._ctrlPressed = evt.ctrlKey;
  48260. _this._altPressed = evt.altKey;
  48261. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48262. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48263. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48264. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48265. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48266. var index = _this._keys.indexOf(evt.keyCode);
  48267. if (index === -1) {
  48268. _this._keys.push(evt.keyCode);
  48269. }
  48270. if (evt.preventDefault) {
  48271. if (!noPreventDefault) {
  48272. evt.preventDefault();
  48273. }
  48274. }
  48275. }
  48276. }
  48277. else {
  48278. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48279. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48280. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48281. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48282. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48283. var index = _this._keys.indexOf(evt.keyCode);
  48284. if (index >= 0) {
  48285. _this._keys.splice(index, 1);
  48286. }
  48287. if (evt.preventDefault) {
  48288. if (!noPreventDefault) {
  48289. evt.preventDefault();
  48290. }
  48291. }
  48292. }
  48293. }
  48294. });
  48295. };
  48296. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48297. if (this._scene) {
  48298. if (this._onKeyboardObserver) {
  48299. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48300. }
  48301. if (this._onCanvasBlurObserver) {
  48302. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48303. }
  48304. this._onKeyboardObserver = null;
  48305. this._onCanvasBlurObserver = null;
  48306. }
  48307. this._keys = [];
  48308. };
  48309. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48310. if (this._onKeyboardObserver) {
  48311. var camera = this.camera;
  48312. for (var index = 0; index < this._keys.length; index++) {
  48313. var keyCode = this._keys[index];
  48314. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48315. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48316. camera.inertialPanningX -= 1 / this.panningSensibility;
  48317. }
  48318. else {
  48319. camera.inertialAlphaOffset -= 0.01;
  48320. }
  48321. }
  48322. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48323. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48324. camera.inertialPanningY += 1 / this.panningSensibility;
  48325. }
  48326. else if (this._altPressed && this.useAltToZoom) {
  48327. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48328. }
  48329. else {
  48330. camera.inertialBetaOffset -= 0.01;
  48331. }
  48332. }
  48333. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48334. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48335. camera.inertialPanningX += 1 / this.panningSensibility;
  48336. }
  48337. else {
  48338. camera.inertialAlphaOffset += 0.01;
  48339. }
  48340. }
  48341. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48342. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48343. camera.inertialPanningY -= 1 / this.panningSensibility;
  48344. }
  48345. else if (this._altPressed && this.useAltToZoom) {
  48346. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48347. }
  48348. else {
  48349. camera.inertialBetaOffset += 0.01;
  48350. }
  48351. }
  48352. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48353. camera.restoreState();
  48354. }
  48355. }
  48356. }
  48357. };
  48358. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48359. return "ArcRotateCameraKeyboardMoveInput";
  48360. };
  48361. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48362. return "keyboard";
  48363. };
  48364. __decorate([
  48365. BABYLON.serialize()
  48366. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48367. __decorate([
  48368. BABYLON.serialize()
  48369. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48370. __decorate([
  48371. BABYLON.serialize()
  48372. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48373. __decorate([
  48374. BABYLON.serialize()
  48375. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48376. __decorate([
  48377. BABYLON.serialize()
  48378. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48379. __decorate([
  48380. BABYLON.serialize()
  48381. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48382. __decorate([
  48383. BABYLON.serialize()
  48384. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48385. __decorate([
  48386. BABYLON.serialize()
  48387. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48388. return ArcRotateCameraKeyboardMoveInput;
  48389. }());
  48390. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48391. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48392. })(BABYLON || (BABYLON = {}));
  48393. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48394. var BABYLON;
  48395. (function (BABYLON) {
  48396. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48397. function ArcRotateCameraMouseWheelInput() {
  48398. this.wheelPrecision = 3.0;
  48399. /**
  48400. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48401. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48402. */
  48403. this.wheelDeltaPercentage = 0;
  48404. }
  48405. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48406. var _this = this;
  48407. this._wheel = function (p, s) {
  48408. //sanity check - this should be a PointerWheel event.
  48409. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48410. return;
  48411. var event = p.event;
  48412. var delta = 0;
  48413. if (event.wheelDelta) {
  48414. if (_this.wheelDeltaPercentage) {
  48415. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48416. if (event.wheelDelta > 0) {
  48417. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48418. }
  48419. else {
  48420. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48421. }
  48422. }
  48423. else {
  48424. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48425. }
  48426. }
  48427. else if (event.detail) {
  48428. delta = -event.detail / _this.wheelPrecision;
  48429. }
  48430. if (delta)
  48431. _this.camera.inertialRadiusOffset += delta;
  48432. if (event.preventDefault) {
  48433. if (!noPreventDefault) {
  48434. event.preventDefault();
  48435. }
  48436. }
  48437. };
  48438. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48439. };
  48440. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48441. if (this._observer && element) {
  48442. this.camera.getScene().onPointerObservable.remove(this._observer);
  48443. this._observer = null;
  48444. this._wheel = null;
  48445. }
  48446. };
  48447. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48448. return "ArcRotateCameraMouseWheelInput";
  48449. };
  48450. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48451. return "mousewheel";
  48452. };
  48453. __decorate([
  48454. BABYLON.serialize()
  48455. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48456. __decorate([
  48457. BABYLON.serialize()
  48458. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48459. return ArcRotateCameraMouseWheelInput;
  48460. }());
  48461. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48462. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48463. })(BABYLON || (BABYLON = {}));
  48464. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48465. var BABYLON;
  48466. (function (BABYLON) {
  48467. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48468. function ArcRotateCameraPointersInput() {
  48469. this.buttons = [0, 1, 2];
  48470. this.angularSensibilityX = 1000.0;
  48471. this.angularSensibilityY = 1000.0;
  48472. this.pinchPrecision = 12.0;
  48473. /**
  48474. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48475. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48476. */
  48477. this.pinchDeltaPercentage = 0;
  48478. this.panningSensibility = 1000.0;
  48479. this.multiTouchPanning = true;
  48480. this.multiTouchPanAndZoom = true;
  48481. this._isPanClick = false;
  48482. this.pinchInwards = true;
  48483. }
  48484. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48485. var _this = this;
  48486. var engine = this.camera.getEngine();
  48487. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48488. var pointA = null;
  48489. var pointB = null;
  48490. var previousPinchSquaredDistance = 0;
  48491. var initialDistance = 0;
  48492. var twoFingerActivityCount = 0;
  48493. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48494. this._pointerInput = function (p, s) {
  48495. var evt = p.event;
  48496. var isTouch = p.event.pointerType === "touch";
  48497. if (engine.isInVRExclusivePointerMode) {
  48498. return;
  48499. }
  48500. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48501. return;
  48502. }
  48503. var srcElement = (evt.srcElement || evt.target);
  48504. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48505. try {
  48506. srcElement.setPointerCapture(evt.pointerId);
  48507. }
  48508. catch (e) {
  48509. //Nothing to do with the error. Execution will continue.
  48510. }
  48511. // Manage panning with pan button click
  48512. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48513. // manage pointers
  48514. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48515. if (pointA === null) {
  48516. pointA = cacheSoloPointer;
  48517. }
  48518. else if (pointB === null) {
  48519. pointB = cacheSoloPointer;
  48520. }
  48521. if (!noPreventDefault) {
  48522. evt.preventDefault();
  48523. element.focus();
  48524. }
  48525. }
  48526. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48527. _this.camera.restoreState();
  48528. }
  48529. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48530. try {
  48531. srcElement.releasePointerCapture(evt.pointerId);
  48532. }
  48533. catch (e) {
  48534. //Nothing to do with the error.
  48535. }
  48536. cacheSoloPointer = null;
  48537. previousPinchSquaredDistance = 0;
  48538. previousMultiTouchPanPosition.isPaning = false;
  48539. previousMultiTouchPanPosition.isPinching = false;
  48540. twoFingerActivityCount = 0;
  48541. initialDistance = 0;
  48542. if (!isTouch) {
  48543. pointB = null; // Mouse and pen are mono pointer
  48544. }
  48545. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48546. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48547. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48548. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48549. if (engine._badOS) {
  48550. pointA = pointB = null;
  48551. }
  48552. else {
  48553. //only remove the impacted pointer in case of multitouch allowing on most
  48554. //platforms switching from rotate to zoom and pan seamlessly.
  48555. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48556. pointA = pointB;
  48557. pointB = null;
  48558. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48559. }
  48560. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48561. pointB = null;
  48562. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48563. }
  48564. else {
  48565. pointA = pointB = null;
  48566. }
  48567. }
  48568. if (!noPreventDefault) {
  48569. evt.preventDefault();
  48570. }
  48571. }
  48572. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48573. if (!noPreventDefault) {
  48574. evt.preventDefault();
  48575. }
  48576. // One button down
  48577. if (pointA && pointB === null && cacheSoloPointer) {
  48578. if (_this.panningSensibility !== 0 &&
  48579. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48580. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48581. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48582. }
  48583. else {
  48584. var offsetX = evt.clientX - cacheSoloPointer.x;
  48585. var offsetY = evt.clientY - cacheSoloPointer.y;
  48586. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48587. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48588. }
  48589. cacheSoloPointer.x = evt.clientX;
  48590. cacheSoloPointer.y = evt.clientY;
  48591. }
  48592. // Two buttons down: pinch/pan
  48593. else if (pointA && pointB) {
  48594. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48595. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48596. ed.x = evt.clientX;
  48597. ed.y = evt.clientY;
  48598. var direction = _this.pinchInwards ? 1 : -1;
  48599. var distX = pointA.x - pointB.x;
  48600. var distY = pointA.y - pointB.y;
  48601. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48602. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48603. if (previousPinchSquaredDistance === 0) {
  48604. initialDistance = pinchDistance;
  48605. previousPinchSquaredDistance = pinchSquaredDistance;
  48606. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48607. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48608. return;
  48609. }
  48610. if (_this.multiTouchPanAndZoom) {
  48611. if (_this.pinchDeltaPercentage) {
  48612. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48613. }
  48614. else {
  48615. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48616. (_this.pinchPrecision *
  48617. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48618. direction);
  48619. }
  48620. if (_this.panningSensibility !== 0) {
  48621. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48622. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48623. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48624. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48625. previousMultiTouchPanPosition.x = pointersCenterX;
  48626. previousMultiTouchPanPosition.y = pointersCenterY;
  48627. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48628. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48629. }
  48630. }
  48631. else {
  48632. twoFingerActivityCount++;
  48633. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48634. if (_this.pinchDeltaPercentage) {
  48635. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48636. }
  48637. else {
  48638. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48639. (_this.pinchPrecision *
  48640. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48641. direction);
  48642. }
  48643. previousMultiTouchPanPosition.isPaning = false;
  48644. previousMultiTouchPanPosition.isPinching = true;
  48645. }
  48646. else {
  48647. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48648. if (!previousMultiTouchPanPosition.isPaning) {
  48649. previousMultiTouchPanPosition.isPaning = true;
  48650. previousMultiTouchPanPosition.isPinching = false;
  48651. previousMultiTouchPanPosition.x = ed.x;
  48652. previousMultiTouchPanPosition.y = ed.y;
  48653. return;
  48654. }
  48655. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48656. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48657. }
  48658. }
  48659. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48660. previousMultiTouchPanPosition.x = ed.x;
  48661. previousMultiTouchPanPosition.y = ed.y;
  48662. }
  48663. }
  48664. previousPinchSquaredDistance = pinchSquaredDistance;
  48665. }
  48666. }
  48667. };
  48668. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48669. this._onContextMenu = function (evt) {
  48670. evt.preventDefault();
  48671. };
  48672. if (!this.camera._useCtrlForPanning) {
  48673. element.addEventListener("contextmenu", this._onContextMenu, false);
  48674. }
  48675. this._onLostFocus = function () {
  48676. //this._keys = [];
  48677. pointA = pointB = null;
  48678. previousPinchSquaredDistance = 0;
  48679. previousMultiTouchPanPosition.isPaning = false;
  48680. previousMultiTouchPanPosition.isPinching = false;
  48681. twoFingerActivityCount = 0;
  48682. cacheSoloPointer = null;
  48683. initialDistance = 0;
  48684. };
  48685. this._onMouseMove = function (evt) {
  48686. if (!engine.isPointerLock) {
  48687. return;
  48688. }
  48689. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48690. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48691. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48692. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48693. if (!noPreventDefault) {
  48694. evt.preventDefault();
  48695. }
  48696. };
  48697. this._onGestureStart = function (e) {
  48698. if (window.MSGesture === undefined) {
  48699. return;
  48700. }
  48701. if (!_this._MSGestureHandler) {
  48702. _this._MSGestureHandler = new MSGesture();
  48703. _this._MSGestureHandler.target = element;
  48704. }
  48705. _this._MSGestureHandler.addPointer(e.pointerId);
  48706. };
  48707. this._onGesture = function (e) {
  48708. _this.camera.radius *= e.scale;
  48709. if (e.preventDefault) {
  48710. if (!noPreventDefault) {
  48711. e.stopPropagation();
  48712. e.preventDefault();
  48713. }
  48714. }
  48715. };
  48716. element.addEventListener("mousemove", this._onMouseMove, false);
  48717. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48718. element.addEventListener("MSGestureChange", this._onGesture, false);
  48719. BABYLON.Tools.RegisterTopRootEvents([
  48720. { name: "blur", handler: this._onLostFocus }
  48721. ]);
  48722. };
  48723. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48724. if (this._onLostFocus) {
  48725. BABYLON.Tools.UnregisterTopRootEvents([
  48726. { name: "blur", handler: this._onLostFocus }
  48727. ]);
  48728. }
  48729. if (element && this._observer) {
  48730. this.camera.getScene().onPointerObservable.remove(this._observer);
  48731. this._observer = null;
  48732. if (this._onContextMenu) {
  48733. element.removeEventListener("contextmenu", this._onContextMenu);
  48734. }
  48735. if (this._onMouseMove) {
  48736. element.removeEventListener("mousemove", this._onMouseMove);
  48737. }
  48738. if (this._onGestureStart) {
  48739. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48740. }
  48741. if (this._onGesture) {
  48742. element.removeEventListener("MSGestureChange", this._onGesture);
  48743. }
  48744. this._isPanClick = false;
  48745. this.pinchInwards = true;
  48746. this._onMouseMove = null;
  48747. this._onGestureStart = null;
  48748. this._onGesture = null;
  48749. this._MSGestureHandler = null;
  48750. this._onLostFocus = null;
  48751. this._onContextMenu = null;
  48752. }
  48753. };
  48754. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48755. return "ArcRotateCameraPointersInput";
  48756. };
  48757. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48758. return "pointers";
  48759. };
  48760. __decorate([
  48761. BABYLON.serialize()
  48762. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48763. __decorate([
  48764. BABYLON.serialize()
  48765. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48766. __decorate([
  48767. BABYLON.serialize()
  48768. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48769. __decorate([
  48770. BABYLON.serialize()
  48771. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48772. __decorate([
  48773. BABYLON.serialize()
  48774. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48775. __decorate([
  48776. BABYLON.serialize()
  48777. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48778. __decorate([
  48779. BABYLON.serialize()
  48780. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48781. __decorate([
  48782. BABYLON.serialize()
  48783. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48784. return ArcRotateCameraPointersInput;
  48785. }());
  48786. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48787. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48788. })(BABYLON || (BABYLON = {}));
  48789. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48790. var BABYLON;
  48791. (function (BABYLON) {
  48792. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48793. __extends(ArcRotateCameraInputsManager, _super);
  48794. function ArcRotateCameraInputsManager(camera) {
  48795. return _super.call(this, camera) || this;
  48796. }
  48797. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48798. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48799. return this;
  48800. };
  48801. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48802. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48803. return this;
  48804. };
  48805. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48806. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48807. return this;
  48808. };
  48809. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48810. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48811. return this;
  48812. };
  48813. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48814. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48815. return this;
  48816. };
  48817. return ArcRotateCameraInputsManager;
  48818. }(BABYLON.CameraInputsManager));
  48819. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48820. })(BABYLON || (BABYLON = {}));
  48821. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48822. var BABYLON;
  48823. (function (BABYLON) {
  48824. var ArcRotateCamera = /** @class */ (function (_super) {
  48825. __extends(ArcRotateCamera, _super);
  48826. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48827. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48828. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48829. _this.inertialAlphaOffset = 0;
  48830. _this.inertialBetaOffset = 0;
  48831. _this.inertialRadiusOffset = 0;
  48832. _this.lowerAlphaLimit = null;
  48833. _this.upperAlphaLimit = null;
  48834. _this.lowerBetaLimit = 0.01;
  48835. _this.upperBetaLimit = Math.PI;
  48836. _this.lowerRadiusLimit = null;
  48837. _this.upperRadiusLimit = null;
  48838. _this.inertialPanningX = 0;
  48839. _this.inertialPanningY = 0;
  48840. _this.pinchToPanMaxDistance = 20;
  48841. _this.panningDistanceLimit = null;
  48842. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48843. _this.panningInertia = 0.9;
  48844. //-- end properties for backward compatibility for inputs
  48845. _this.zoomOnFactor = 1;
  48846. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48847. _this.allowUpsideDown = true;
  48848. _this._viewMatrix = new BABYLON.Matrix();
  48849. // Panning
  48850. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48851. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48852. _this.checkCollisions = false;
  48853. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48854. _this._previousPosition = BABYLON.Vector3.Zero();
  48855. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48856. _this._newPosition = BABYLON.Vector3.Zero();
  48857. _this._computationVector = BABYLON.Vector3.Zero();
  48858. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48859. if (collidedMesh === void 0) { collidedMesh = null; }
  48860. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48861. newPosition.multiplyInPlace(_this._collider._radius);
  48862. }
  48863. if (!collidedMesh) {
  48864. _this._previousPosition.copyFrom(_this.position);
  48865. }
  48866. else {
  48867. _this.setPosition(newPosition);
  48868. if (_this.onCollide) {
  48869. _this.onCollide(collidedMesh);
  48870. }
  48871. }
  48872. // Recompute because of constraints
  48873. var cosa = Math.cos(_this.alpha);
  48874. var sina = Math.sin(_this.alpha);
  48875. var cosb = Math.cos(_this.beta);
  48876. var sinb = Math.sin(_this.beta);
  48877. if (sinb === 0) {
  48878. sinb = 0.0001;
  48879. }
  48880. var target = _this._getTargetPosition();
  48881. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48882. target.addToRef(_this._computationVector, _this._newPosition);
  48883. _this.position.copyFrom(_this._newPosition);
  48884. var up = _this.upVector;
  48885. if (_this.allowUpsideDown && _this.beta < 0) {
  48886. up = up.clone();
  48887. up = up.negate();
  48888. }
  48889. _this._computeViewMatrix(_this.position, target, up);
  48890. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48891. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48892. _this._collisionTriggered = false;
  48893. };
  48894. _this._target = BABYLON.Vector3.Zero();
  48895. if (target) {
  48896. _this.setTarget(target);
  48897. }
  48898. _this.alpha = alpha;
  48899. _this.beta = beta;
  48900. _this.radius = radius;
  48901. _this.getViewMatrix();
  48902. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48903. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48904. return _this;
  48905. }
  48906. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48907. get: function () {
  48908. return this._target;
  48909. },
  48910. set: function (value) {
  48911. this.setTarget(value);
  48912. },
  48913. enumerable: true,
  48914. configurable: true
  48915. });
  48916. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48917. //-- begin properties for backward compatibility for inputs
  48918. get: function () {
  48919. var pointers = this.inputs.attached["pointers"];
  48920. if (pointers)
  48921. return pointers.angularSensibilityX;
  48922. return 0;
  48923. },
  48924. set: function (value) {
  48925. var pointers = this.inputs.attached["pointers"];
  48926. if (pointers) {
  48927. pointers.angularSensibilityX = value;
  48928. }
  48929. },
  48930. enumerable: true,
  48931. configurable: true
  48932. });
  48933. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48934. get: function () {
  48935. var pointers = this.inputs.attached["pointers"];
  48936. if (pointers)
  48937. return pointers.angularSensibilityY;
  48938. return 0;
  48939. },
  48940. set: function (value) {
  48941. var pointers = this.inputs.attached["pointers"];
  48942. if (pointers) {
  48943. pointers.angularSensibilityY = value;
  48944. }
  48945. },
  48946. enumerable: true,
  48947. configurable: true
  48948. });
  48949. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48950. get: function () {
  48951. var pointers = this.inputs.attached["pointers"];
  48952. if (pointers)
  48953. return pointers.pinchPrecision;
  48954. return 0;
  48955. },
  48956. set: function (value) {
  48957. var pointers = this.inputs.attached["pointers"];
  48958. if (pointers) {
  48959. pointers.pinchPrecision = value;
  48960. }
  48961. },
  48962. enumerable: true,
  48963. configurable: true
  48964. });
  48965. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48966. get: function () {
  48967. var pointers = this.inputs.attached["pointers"];
  48968. if (pointers)
  48969. return pointers.pinchDeltaPercentage;
  48970. return 0;
  48971. },
  48972. set: function (value) {
  48973. var pointers = this.inputs.attached["pointers"];
  48974. if (pointers) {
  48975. pointers.pinchDeltaPercentage = value;
  48976. }
  48977. },
  48978. enumerable: true,
  48979. configurable: true
  48980. });
  48981. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48982. get: function () {
  48983. var pointers = this.inputs.attached["pointers"];
  48984. if (pointers)
  48985. return pointers.panningSensibility;
  48986. return 0;
  48987. },
  48988. set: function (value) {
  48989. var pointers = this.inputs.attached["pointers"];
  48990. if (pointers) {
  48991. pointers.panningSensibility = value;
  48992. }
  48993. },
  48994. enumerable: true,
  48995. configurable: true
  48996. });
  48997. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48998. get: function () {
  48999. var keyboard = this.inputs.attached["keyboard"];
  49000. if (keyboard)
  49001. return keyboard.keysUp;
  49002. return [];
  49003. },
  49004. set: function (value) {
  49005. var keyboard = this.inputs.attached["keyboard"];
  49006. if (keyboard)
  49007. keyboard.keysUp = value;
  49008. },
  49009. enumerable: true,
  49010. configurable: true
  49011. });
  49012. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49013. get: function () {
  49014. var keyboard = this.inputs.attached["keyboard"];
  49015. if (keyboard)
  49016. return keyboard.keysDown;
  49017. return [];
  49018. },
  49019. set: function (value) {
  49020. var keyboard = this.inputs.attached["keyboard"];
  49021. if (keyboard)
  49022. keyboard.keysDown = value;
  49023. },
  49024. enumerable: true,
  49025. configurable: true
  49026. });
  49027. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49028. get: function () {
  49029. var keyboard = this.inputs.attached["keyboard"];
  49030. if (keyboard)
  49031. return keyboard.keysLeft;
  49032. return [];
  49033. },
  49034. set: function (value) {
  49035. var keyboard = this.inputs.attached["keyboard"];
  49036. if (keyboard)
  49037. keyboard.keysLeft = value;
  49038. },
  49039. enumerable: true,
  49040. configurable: true
  49041. });
  49042. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49043. get: function () {
  49044. var keyboard = this.inputs.attached["keyboard"];
  49045. if (keyboard)
  49046. return keyboard.keysRight;
  49047. return [];
  49048. },
  49049. set: function (value) {
  49050. var keyboard = this.inputs.attached["keyboard"];
  49051. if (keyboard)
  49052. keyboard.keysRight = value;
  49053. },
  49054. enumerable: true,
  49055. configurable: true
  49056. });
  49057. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49058. get: function () {
  49059. var mousewheel = this.inputs.attached["mousewheel"];
  49060. if (mousewheel)
  49061. return mousewheel.wheelPrecision;
  49062. return 0;
  49063. },
  49064. set: function (value) {
  49065. var mousewheel = this.inputs.attached["mousewheel"];
  49066. if (mousewheel)
  49067. mousewheel.wheelPrecision = value;
  49068. },
  49069. enumerable: true,
  49070. configurable: true
  49071. });
  49072. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49073. get: function () {
  49074. var mousewheel = this.inputs.attached["mousewheel"];
  49075. if (mousewheel)
  49076. return mousewheel.wheelDeltaPercentage;
  49077. return 0;
  49078. },
  49079. set: function (value) {
  49080. var mousewheel = this.inputs.attached["mousewheel"];
  49081. if (mousewheel)
  49082. mousewheel.wheelDeltaPercentage = value;
  49083. },
  49084. enumerable: true,
  49085. configurable: true
  49086. });
  49087. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49088. get: function () {
  49089. return this._bouncingBehavior;
  49090. },
  49091. enumerable: true,
  49092. configurable: true
  49093. });
  49094. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49095. get: function () {
  49096. return this._bouncingBehavior != null;
  49097. },
  49098. set: function (value) {
  49099. if (value === this.useBouncingBehavior) {
  49100. return;
  49101. }
  49102. if (value) {
  49103. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49104. this.addBehavior(this._bouncingBehavior);
  49105. }
  49106. else if (this._bouncingBehavior) {
  49107. this.removeBehavior(this._bouncingBehavior);
  49108. this._bouncingBehavior = null;
  49109. }
  49110. },
  49111. enumerable: true,
  49112. configurable: true
  49113. });
  49114. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49115. get: function () {
  49116. return this._framingBehavior;
  49117. },
  49118. enumerable: true,
  49119. configurable: true
  49120. });
  49121. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49122. get: function () {
  49123. return this._framingBehavior != null;
  49124. },
  49125. set: function (value) {
  49126. if (value === this.useFramingBehavior) {
  49127. return;
  49128. }
  49129. if (value) {
  49130. this._framingBehavior = new BABYLON.FramingBehavior();
  49131. this.addBehavior(this._framingBehavior);
  49132. }
  49133. else if (this._framingBehavior) {
  49134. this.removeBehavior(this._framingBehavior);
  49135. this._framingBehavior = null;
  49136. }
  49137. },
  49138. enumerable: true,
  49139. configurable: true
  49140. });
  49141. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49142. get: function () {
  49143. return this._autoRotationBehavior;
  49144. },
  49145. enumerable: true,
  49146. configurable: true
  49147. });
  49148. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49149. get: function () {
  49150. return this._autoRotationBehavior != null;
  49151. },
  49152. set: function (value) {
  49153. if (value === this.useAutoRotationBehavior) {
  49154. return;
  49155. }
  49156. if (value) {
  49157. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49158. this.addBehavior(this._autoRotationBehavior);
  49159. }
  49160. else if (this._autoRotationBehavior) {
  49161. this.removeBehavior(this._autoRotationBehavior);
  49162. this._autoRotationBehavior = null;
  49163. }
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. // Cache
  49169. ArcRotateCamera.prototype._initCache = function () {
  49170. _super.prototype._initCache.call(this);
  49171. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49172. this._cache.alpha = undefined;
  49173. this._cache.beta = undefined;
  49174. this._cache.radius = undefined;
  49175. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49176. };
  49177. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49178. if (!ignoreParentClass) {
  49179. _super.prototype._updateCache.call(this);
  49180. }
  49181. this._cache._target.copyFrom(this._getTargetPosition());
  49182. this._cache.alpha = this.alpha;
  49183. this._cache.beta = this.beta;
  49184. this._cache.radius = this.radius;
  49185. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49186. };
  49187. ArcRotateCamera.prototype._getTargetPosition = function () {
  49188. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49189. var pos = this._targetHost.getAbsolutePosition();
  49190. if (this._targetBoundingCenter) {
  49191. pos.addToRef(this._targetBoundingCenter, this._target);
  49192. }
  49193. else {
  49194. this._target.copyFrom(pos);
  49195. }
  49196. }
  49197. var lockedTargetPosition = this._getLockedTargetPosition();
  49198. if (lockedTargetPosition) {
  49199. return lockedTargetPosition;
  49200. }
  49201. return this._target;
  49202. };
  49203. ArcRotateCamera.prototype.storeState = function () {
  49204. this._storedAlpha = this.alpha;
  49205. this._storedBeta = this.beta;
  49206. this._storedRadius = this.radius;
  49207. this._storedTarget = this._getTargetPosition().clone();
  49208. return _super.prototype.storeState.call(this);
  49209. };
  49210. /**
  49211. * Restored camera state. You must call storeState() first
  49212. */
  49213. ArcRotateCamera.prototype._restoreStateValues = function () {
  49214. if (!_super.prototype._restoreStateValues.call(this)) {
  49215. return false;
  49216. }
  49217. this.alpha = this._storedAlpha;
  49218. this.beta = this._storedBeta;
  49219. this.radius = this._storedRadius;
  49220. this.setTarget(this._storedTarget.clone());
  49221. this.inertialAlphaOffset = 0;
  49222. this.inertialBetaOffset = 0;
  49223. this.inertialRadiusOffset = 0;
  49224. this.inertialPanningX = 0;
  49225. this.inertialPanningY = 0;
  49226. return true;
  49227. };
  49228. // Synchronized
  49229. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49230. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49231. return false;
  49232. return this._cache._target.equals(this._getTargetPosition())
  49233. && this._cache.alpha === this.alpha
  49234. && this._cache.beta === this.beta
  49235. && this._cache.radius === this.radius
  49236. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49237. };
  49238. // Methods
  49239. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49240. var _this = this;
  49241. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49242. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49243. this._useCtrlForPanning = useCtrlForPanning;
  49244. this._panningMouseButton = panningMouseButton;
  49245. this.inputs.attachElement(element, noPreventDefault);
  49246. this._reset = function () {
  49247. _this.inertialAlphaOffset = 0;
  49248. _this.inertialBetaOffset = 0;
  49249. _this.inertialRadiusOffset = 0;
  49250. _this.inertialPanningX = 0;
  49251. _this.inertialPanningY = 0;
  49252. };
  49253. };
  49254. ArcRotateCamera.prototype.detachControl = function (element) {
  49255. this.inputs.detachElement(element);
  49256. if (this._reset) {
  49257. this._reset();
  49258. }
  49259. };
  49260. ArcRotateCamera.prototype._checkInputs = function () {
  49261. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49262. if (this._collisionTriggered) {
  49263. return;
  49264. }
  49265. this.inputs.checkInputs();
  49266. // Inertia
  49267. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49268. var inertialAlphaOffset = this.inertialAlphaOffset;
  49269. if (this.beta <= 0)
  49270. inertialAlphaOffset *= -1;
  49271. if (this.getScene().useRightHandedSystem)
  49272. inertialAlphaOffset *= -1;
  49273. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49274. inertialAlphaOffset *= -1;
  49275. this.alpha += inertialAlphaOffset;
  49276. this.beta += this.inertialBetaOffset;
  49277. this.radius -= this.inertialRadiusOffset;
  49278. this.inertialAlphaOffset *= this.inertia;
  49279. this.inertialBetaOffset *= this.inertia;
  49280. this.inertialRadiusOffset *= this.inertia;
  49281. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49282. this.inertialAlphaOffset = 0;
  49283. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49284. this.inertialBetaOffset = 0;
  49285. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49286. this.inertialRadiusOffset = 0;
  49287. }
  49288. // Panning inertia
  49289. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49290. if (!this._localDirection) {
  49291. this._localDirection = BABYLON.Vector3.Zero();
  49292. this._transformedDirection = BABYLON.Vector3.Zero();
  49293. }
  49294. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49295. this._localDirection.multiplyInPlace(this.panningAxis);
  49296. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49297. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49298. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49299. if (!this.panningAxis.y) {
  49300. this._transformedDirection.y = 0;
  49301. }
  49302. if (!this._targetHost) {
  49303. if (this.panningDistanceLimit) {
  49304. this._transformedDirection.addInPlace(this._target);
  49305. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49306. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49307. this._target.copyFrom(this._transformedDirection);
  49308. }
  49309. }
  49310. else {
  49311. this._target.addInPlace(this._transformedDirection);
  49312. }
  49313. }
  49314. this.inertialPanningX *= this.panningInertia;
  49315. this.inertialPanningY *= this.panningInertia;
  49316. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49317. this.inertialPanningX = 0;
  49318. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49319. this.inertialPanningY = 0;
  49320. }
  49321. // Limits
  49322. this._checkLimits();
  49323. _super.prototype._checkInputs.call(this);
  49324. };
  49325. ArcRotateCamera.prototype._checkLimits = function () {
  49326. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49327. if (this.allowUpsideDown && this.beta > Math.PI) {
  49328. this.beta = this.beta - (2 * Math.PI);
  49329. }
  49330. }
  49331. else {
  49332. if (this.beta < this.lowerBetaLimit) {
  49333. this.beta = this.lowerBetaLimit;
  49334. }
  49335. }
  49336. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49337. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49338. this.beta = this.beta + (2 * Math.PI);
  49339. }
  49340. }
  49341. else {
  49342. if (this.beta > this.upperBetaLimit) {
  49343. this.beta = this.upperBetaLimit;
  49344. }
  49345. }
  49346. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49347. this.alpha = this.lowerAlphaLimit;
  49348. }
  49349. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49350. this.alpha = this.upperAlphaLimit;
  49351. }
  49352. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49353. this.radius = this.lowerRadiusLimit;
  49354. }
  49355. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49356. this.radius = this.upperRadiusLimit;
  49357. }
  49358. };
  49359. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49360. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49361. this.radius = this._computationVector.length();
  49362. if (this.radius === 0) {
  49363. this.radius = 0.0001; // Just to avoid division by zero
  49364. }
  49365. // Alpha
  49366. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49367. if (this._computationVector.z < 0) {
  49368. this.alpha = 2 * Math.PI - this.alpha;
  49369. }
  49370. // Beta
  49371. this.beta = Math.acos(this._computationVector.y / this.radius);
  49372. this._checkLimits();
  49373. };
  49374. ArcRotateCamera.prototype.setPosition = function (position) {
  49375. if (this.position.equals(position)) {
  49376. return;
  49377. }
  49378. this.position.copyFrom(position);
  49379. this.rebuildAnglesAndRadius();
  49380. };
  49381. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49382. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49383. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49384. if (target.getBoundingInfo) {
  49385. if (toBoundingCenter) {
  49386. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49387. }
  49388. else {
  49389. this._targetBoundingCenter = null;
  49390. }
  49391. this._targetHost = target;
  49392. this._target = this._getTargetPosition();
  49393. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49394. }
  49395. else {
  49396. var newTarget = target;
  49397. var currentTarget = this._getTargetPosition();
  49398. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49399. return;
  49400. }
  49401. this._targetHost = null;
  49402. this._target = newTarget;
  49403. this._targetBoundingCenter = null;
  49404. this.onMeshTargetChangedObservable.notifyObservers(null);
  49405. }
  49406. this.rebuildAnglesAndRadius();
  49407. };
  49408. ArcRotateCamera.prototype._getViewMatrix = function () {
  49409. // Compute
  49410. var cosa = Math.cos(this.alpha);
  49411. var sina = Math.sin(this.alpha);
  49412. var cosb = Math.cos(this.beta);
  49413. var sinb = Math.sin(this.beta);
  49414. if (sinb === 0) {
  49415. sinb = 0.0001;
  49416. }
  49417. var target = this._getTargetPosition();
  49418. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49419. target.addToRef(this._computationVector, this._newPosition);
  49420. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49421. if (!this._collider) {
  49422. this._collider = new BABYLON.Collider();
  49423. }
  49424. this._collider._radius = this.collisionRadius;
  49425. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49426. this._collisionTriggered = true;
  49427. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49428. }
  49429. else {
  49430. this.position.copyFrom(this._newPosition);
  49431. var up = this.upVector;
  49432. if (this.allowUpsideDown && sinb < 0) {
  49433. up = up.clone();
  49434. up = up.negate();
  49435. }
  49436. this._computeViewMatrix(this.position, target, up);
  49437. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49438. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49439. }
  49440. this._currentTarget = target;
  49441. return this._viewMatrix;
  49442. };
  49443. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49444. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49445. meshes = meshes || this.getScene().meshes;
  49446. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49447. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49448. this.radius = distance * this.zoomOnFactor;
  49449. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49450. };
  49451. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49452. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49453. var meshesOrMinMaxVector;
  49454. var distance;
  49455. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49456. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49457. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49458. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49459. }
  49460. else { //minMaxVector and distance
  49461. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49462. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49463. distance = minMaxVectorAndDistance.distance;
  49464. }
  49465. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49466. if (!doNotUpdateMaxZ) {
  49467. this.maxZ = distance * 2;
  49468. }
  49469. };
  49470. /**
  49471. * @override
  49472. * Override Camera.createRigCamera
  49473. */
  49474. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49475. var alphaShift = 0;
  49476. switch (this.cameraRigMode) {
  49477. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49478. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49479. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49480. case BABYLON.Camera.RIG_MODE_VR:
  49481. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49482. break;
  49483. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49484. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49485. break;
  49486. }
  49487. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49488. rigCam._cameraRigParams = {};
  49489. return rigCam;
  49490. };
  49491. /**
  49492. * @override
  49493. * Override Camera._updateRigCameras
  49494. */
  49495. ArcRotateCamera.prototype._updateRigCameras = function () {
  49496. var camLeft = this._rigCameras[0];
  49497. var camRight = this._rigCameras[1];
  49498. camLeft.beta = camRight.beta = this.beta;
  49499. camLeft.radius = camRight.radius = this.radius;
  49500. switch (this.cameraRigMode) {
  49501. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49503. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49504. case BABYLON.Camera.RIG_MODE_VR:
  49505. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49506. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49507. break;
  49508. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49509. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49510. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49511. break;
  49512. }
  49513. _super.prototype._updateRigCameras.call(this);
  49514. };
  49515. ArcRotateCamera.prototype.dispose = function () {
  49516. this.inputs.clear();
  49517. _super.prototype.dispose.call(this);
  49518. };
  49519. ArcRotateCamera.prototype.getClassName = function () {
  49520. return "ArcRotateCamera";
  49521. };
  49522. __decorate([
  49523. BABYLON.serialize()
  49524. ], ArcRotateCamera.prototype, "alpha", void 0);
  49525. __decorate([
  49526. BABYLON.serialize()
  49527. ], ArcRotateCamera.prototype, "beta", void 0);
  49528. __decorate([
  49529. BABYLON.serialize()
  49530. ], ArcRotateCamera.prototype, "radius", void 0);
  49531. __decorate([
  49532. BABYLON.serializeAsVector3("target")
  49533. ], ArcRotateCamera.prototype, "_target", void 0);
  49534. __decorate([
  49535. BABYLON.serialize()
  49536. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49537. __decorate([
  49538. BABYLON.serialize()
  49539. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49540. __decorate([
  49541. BABYLON.serialize()
  49542. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49543. __decorate([
  49544. BABYLON.serialize()
  49545. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49546. __decorate([
  49547. BABYLON.serialize()
  49548. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49549. __decorate([
  49550. BABYLON.serialize()
  49551. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49552. __decorate([
  49553. BABYLON.serialize()
  49554. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49555. __decorate([
  49556. BABYLON.serialize()
  49557. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49558. __decorate([
  49559. BABYLON.serialize()
  49560. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49561. __decorate([
  49562. BABYLON.serialize()
  49563. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49564. __decorate([
  49565. BABYLON.serialize()
  49566. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49567. __decorate([
  49568. BABYLON.serialize()
  49569. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49570. __decorate([
  49571. BABYLON.serialize()
  49572. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49573. __decorate([
  49574. BABYLON.serializeAsVector3()
  49575. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49576. __decorate([
  49577. BABYLON.serialize()
  49578. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49579. __decorate([
  49580. BABYLON.serialize()
  49581. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49582. __decorate([
  49583. BABYLON.serialize()
  49584. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49585. return ArcRotateCamera;
  49586. }(BABYLON.TargetCamera));
  49587. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49588. })(BABYLON || (BABYLON = {}));
  49589. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49590. var BABYLON;
  49591. (function (BABYLON) {
  49592. /**
  49593. * The HemisphericLight simulates the ambient environment light,
  49594. * so the passed direction is the light reflection direction, not the incoming direction.
  49595. */
  49596. var HemisphericLight = /** @class */ (function (_super) {
  49597. __extends(HemisphericLight, _super);
  49598. /**
  49599. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49600. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49601. * The HemisphericLight can't cast shadows.
  49602. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49603. * @param name The friendly name of the light
  49604. * @param direction The direction of the light reflection
  49605. * @param scene The scene the light belongs to
  49606. */
  49607. function HemisphericLight(name, direction, scene) {
  49608. var _this = _super.call(this, name, scene) || this;
  49609. /**
  49610. * The groundColor is the light in the opposite direction to the one specified during creation.
  49611. * 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.
  49612. */
  49613. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49614. _this.direction = direction || BABYLON.Vector3.Up();
  49615. return _this;
  49616. }
  49617. HemisphericLight.prototype._buildUniformLayout = function () {
  49618. this._uniformBuffer.addUniform("vLightData", 4);
  49619. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49620. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49621. this._uniformBuffer.addUniform("vLightGround", 3);
  49622. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49623. this._uniformBuffer.addUniform("depthValues", 2);
  49624. this._uniformBuffer.create();
  49625. };
  49626. /**
  49627. * Returns the string "HemisphericLight".
  49628. * @return The class name
  49629. */
  49630. HemisphericLight.prototype.getClassName = function () {
  49631. return "HemisphericLight";
  49632. };
  49633. /**
  49634. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49635. * Returns the updated direction.
  49636. * @param target The target the direction should point to
  49637. * @return The computed direction
  49638. */
  49639. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49640. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49641. return this.direction;
  49642. };
  49643. /**
  49644. * Returns the shadow generator associated to the light.
  49645. * @returns Always null for hemispheric lights because it does not support shadows.
  49646. */
  49647. HemisphericLight.prototype.getShadowGenerator = function () {
  49648. return null;
  49649. };
  49650. /**
  49651. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49652. * @param effect The effect to update
  49653. * @param lightIndex The index of the light in the effect to update
  49654. * @returns The hemispheric light
  49655. */
  49656. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49657. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49658. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49659. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49660. return this;
  49661. };
  49662. /**
  49663. * @hidden internal use only.
  49664. */
  49665. HemisphericLight.prototype._getWorldMatrix = function () {
  49666. if (!this._worldMatrix) {
  49667. this._worldMatrix = BABYLON.Matrix.Identity();
  49668. }
  49669. return this._worldMatrix;
  49670. };
  49671. /**
  49672. * Returns the integer 3.
  49673. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49674. */
  49675. HemisphericLight.prototype.getTypeID = function () {
  49676. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49677. };
  49678. __decorate([
  49679. BABYLON.serializeAsColor3()
  49680. ], HemisphericLight.prototype, "groundColor", void 0);
  49681. __decorate([
  49682. BABYLON.serializeAsVector3()
  49683. ], HemisphericLight.prototype, "direction", void 0);
  49684. return HemisphericLight;
  49685. }(BABYLON.Light));
  49686. BABYLON.HemisphericLight = HemisphericLight;
  49687. })(BABYLON || (BABYLON = {}));
  49688. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49689. var BABYLON;
  49690. (function (BABYLON) {
  49691. /**
  49692. * Base implementation IShadowLight
  49693. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49694. */
  49695. var ShadowLight = /** @class */ (function (_super) {
  49696. __extends(ShadowLight, _super);
  49697. function ShadowLight() {
  49698. var _this = _super !== null && _super.apply(this, arguments) || this;
  49699. _this._needProjectionMatrixCompute = true;
  49700. return _this;
  49701. }
  49702. ShadowLight.prototype._setPosition = function (value) {
  49703. this._position = value;
  49704. };
  49705. Object.defineProperty(ShadowLight.prototype, "position", {
  49706. /**
  49707. * Sets the position the shadow will be casted from. Also use as the light position for both
  49708. * point and spot lights.
  49709. */
  49710. get: function () {
  49711. return this._position;
  49712. },
  49713. /**
  49714. * Sets the position the shadow will be casted from. Also use as the light position for both
  49715. * point and spot lights.
  49716. */
  49717. set: function (value) {
  49718. this._setPosition(value);
  49719. },
  49720. enumerable: true,
  49721. configurable: true
  49722. });
  49723. ShadowLight.prototype._setDirection = function (value) {
  49724. this._direction = value;
  49725. };
  49726. Object.defineProperty(ShadowLight.prototype, "direction", {
  49727. /**
  49728. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49729. * Also use as the light direction on spot and directional lights.
  49730. */
  49731. get: function () {
  49732. return this._direction;
  49733. },
  49734. /**
  49735. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49736. * Also use as the light direction on spot and directional lights.
  49737. */
  49738. set: function (value) {
  49739. this._setDirection(value);
  49740. },
  49741. enumerable: true,
  49742. configurable: true
  49743. });
  49744. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49745. /**
  49746. * Gets the shadow projection clipping minimum z value.
  49747. */
  49748. get: function () {
  49749. return this._shadowMinZ;
  49750. },
  49751. /**
  49752. * Sets the shadow projection clipping minimum z value.
  49753. */
  49754. set: function (value) {
  49755. this._shadowMinZ = value;
  49756. this.forceProjectionMatrixCompute();
  49757. },
  49758. enumerable: true,
  49759. configurable: true
  49760. });
  49761. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49762. /**
  49763. * Sets the shadow projection clipping maximum z value.
  49764. */
  49765. get: function () {
  49766. return this._shadowMaxZ;
  49767. },
  49768. /**
  49769. * Gets the shadow projection clipping maximum z value.
  49770. */
  49771. set: function (value) {
  49772. this._shadowMaxZ = value;
  49773. this.forceProjectionMatrixCompute();
  49774. },
  49775. enumerable: true,
  49776. configurable: true
  49777. });
  49778. /**
  49779. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49780. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49781. */
  49782. ShadowLight.prototype.computeTransformedInformation = function () {
  49783. if (this.parent && this.parent.getWorldMatrix) {
  49784. if (!this.transformedPosition) {
  49785. this.transformedPosition = BABYLON.Vector3.Zero();
  49786. }
  49787. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49788. // In case the direction is present.
  49789. if (this.direction) {
  49790. if (!this.transformedDirection) {
  49791. this.transformedDirection = BABYLON.Vector3.Zero();
  49792. }
  49793. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49794. }
  49795. return true;
  49796. }
  49797. return false;
  49798. };
  49799. /**
  49800. * Return the depth scale used for the shadow map.
  49801. * @returns the depth scale.
  49802. */
  49803. ShadowLight.prototype.getDepthScale = function () {
  49804. return 50.0;
  49805. };
  49806. /**
  49807. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49808. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49809. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49810. */
  49811. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49812. return this.transformedDirection ? this.transformedDirection : this.direction;
  49813. };
  49814. /**
  49815. * Returns the ShadowLight absolute position in the World.
  49816. * @returns the position vector in world space
  49817. */
  49818. ShadowLight.prototype.getAbsolutePosition = function () {
  49819. return this.transformedPosition ? this.transformedPosition : this.position;
  49820. };
  49821. /**
  49822. * Sets the ShadowLight direction toward the passed target.
  49823. * @param target The point tot target in local space
  49824. * @returns the updated ShadowLight direction
  49825. */
  49826. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49827. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49828. return this.direction;
  49829. };
  49830. /**
  49831. * Returns the light rotation in euler definition.
  49832. * @returns the x y z rotation in local space.
  49833. */
  49834. ShadowLight.prototype.getRotation = function () {
  49835. this.direction.normalize();
  49836. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49837. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49838. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49839. };
  49840. /**
  49841. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49842. * @returns true if a cube texture needs to be use
  49843. */
  49844. ShadowLight.prototype.needCube = function () {
  49845. return false;
  49846. };
  49847. /**
  49848. * Detects if the projection matrix requires to be recomputed this frame.
  49849. * @returns true if it requires to be recomputed otherwise, false.
  49850. */
  49851. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49852. return this._needProjectionMatrixCompute;
  49853. };
  49854. /**
  49855. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49856. */
  49857. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49858. this._needProjectionMatrixCompute = true;
  49859. };
  49860. /**
  49861. * Get the world matrix of the sahdow lights.
  49862. * @hidden Internal Use Only
  49863. */
  49864. ShadowLight.prototype._getWorldMatrix = function () {
  49865. if (!this._worldMatrix) {
  49866. this._worldMatrix = BABYLON.Matrix.Identity();
  49867. }
  49868. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49869. return this._worldMatrix;
  49870. };
  49871. /**
  49872. * Gets the minZ used for shadow according to both the scene and the light.
  49873. * @param activeCamera The camera we are returning the min for
  49874. * @returns the depth min z
  49875. */
  49876. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49877. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49878. };
  49879. /**
  49880. * Gets the maxZ used for shadow according to both the scene and the light.
  49881. * @param activeCamera The camera we are returning the max for
  49882. * @returns the depth max z
  49883. */
  49884. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49885. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49886. };
  49887. /**
  49888. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49889. * @param matrix The materix to updated with the projection information
  49890. * @param viewMatrix The transform matrix of the light
  49891. * @param renderList The list of mesh to render in the map
  49892. * @returns The current light
  49893. */
  49894. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49895. if (this.customProjectionMatrixBuilder) {
  49896. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49897. }
  49898. else {
  49899. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49900. }
  49901. return this;
  49902. };
  49903. __decorate([
  49904. BABYLON.serializeAsVector3()
  49905. ], ShadowLight.prototype, "position", null);
  49906. __decorate([
  49907. BABYLON.serializeAsVector3()
  49908. ], ShadowLight.prototype, "direction", null);
  49909. __decorate([
  49910. BABYLON.serialize()
  49911. ], ShadowLight.prototype, "shadowMinZ", null);
  49912. __decorate([
  49913. BABYLON.serialize()
  49914. ], ShadowLight.prototype, "shadowMaxZ", null);
  49915. return ShadowLight;
  49916. }(BABYLON.Light));
  49917. BABYLON.ShadowLight = ShadowLight;
  49918. })(BABYLON || (BABYLON = {}));
  49919. //# sourceMappingURL=babylon.shadowLight.js.map
  49920. var BABYLON;
  49921. (function (BABYLON) {
  49922. /**
  49923. * A point light is a light defined by an unique point in world space.
  49924. * The light is emitted in every direction from this point.
  49925. * A good example of a point light is a standard light bulb.
  49926. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49927. */
  49928. var PointLight = /** @class */ (function (_super) {
  49929. __extends(PointLight, _super);
  49930. /**
  49931. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49932. * A PointLight emits the light in every direction.
  49933. * It can cast shadows.
  49934. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49935. * ```javascript
  49936. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49937. * ```
  49938. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49939. * @param name The light friendly name
  49940. * @param position The position of the point light in the scene
  49941. * @param scene The scene the lights belongs to
  49942. */
  49943. function PointLight(name, position, scene) {
  49944. var _this = _super.call(this, name, scene) || this;
  49945. _this._shadowAngle = Math.PI / 2;
  49946. _this.position = position;
  49947. return _this;
  49948. }
  49949. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49950. /**
  49951. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49952. * This specifies what angle the shadow will use to be created.
  49953. *
  49954. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49955. */
  49956. get: function () {
  49957. return this._shadowAngle;
  49958. },
  49959. /**
  49960. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49961. * This specifies what angle the shadow will use to be created.
  49962. *
  49963. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49964. */
  49965. set: function (value) {
  49966. this._shadowAngle = value;
  49967. this.forceProjectionMatrixCompute();
  49968. },
  49969. enumerable: true,
  49970. configurable: true
  49971. });
  49972. Object.defineProperty(PointLight.prototype, "direction", {
  49973. /**
  49974. * Gets the direction if it has been set.
  49975. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49976. */
  49977. get: function () {
  49978. return this._direction;
  49979. },
  49980. /**
  49981. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49982. */
  49983. set: function (value) {
  49984. var previousNeedCube = this.needCube();
  49985. this._direction = value;
  49986. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49987. this._shadowGenerator.recreateShadowMap();
  49988. }
  49989. },
  49990. enumerable: true,
  49991. configurable: true
  49992. });
  49993. /**
  49994. * Returns the string "PointLight"
  49995. * @returns the class name
  49996. */
  49997. PointLight.prototype.getClassName = function () {
  49998. return "PointLight";
  49999. };
  50000. /**
  50001. * Returns the integer 0.
  50002. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50003. */
  50004. PointLight.prototype.getTypeID = function () {
  50005. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50006. };
  50007. /**
  50008. * Specifies wether or not the shadowmap should be a cube texture.
  50009. * @returns true if the shadowmap needs to be a cube texture.
  50010. */
  50011. PointLight.prototype.needCube = function () {
  50012. return !this.direction;
  50013. };
  50014. /**
  50015. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50016. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50017. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50018. */
  50019. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50020. if (this.direction) {
  50021. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50022. }
  50023. else {
  50024. switch (faceIndex) {
  50025. case 0:
  50026. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50027. case 1:
  50028. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50029. case 2:
  50030. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50031. case 3:
  50032. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50033. case 4:
  50034. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50035. case 5:
  50036. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50037. }
  50038. }
  50039. return BABYLON.Vector3.Zero();
  50040. };
  50041. /**
  50042. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50043. * - fov = PI / 2
  50044. * - aspect ratio : 1.0
  50045. * - z-near and far equal to the active camera minZ and maxZ.
  50046. * Returns the PointLight.
  50047. */
  50048. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50049. var activeCamera = this.getScene().activeCamera;
  50050. if (!activeCamera) {
  50051. return;
  50052. }
  50053. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50054. };
  50055. PointLight.prototype._buildUniformLayout = function () {
  50056. this._uniformBuffer.addUniform("vLightData", 4);
  50057. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50058. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50059. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50060. this._uniformBuffer.addUniform("depthValues", 2);
  50061. this._uniformBuffer.create();
  50062. };
  50063. /**
  50064. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50065. * @param effect The effect to update
  50066. * @param lightIndex The index of the light in the effect to update
  50067. * @returns The point light
  50068. */
  50069. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50070. if (this.computeTransformedInformation()) {
  50071. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50072. return this;
  50073. }
  50074. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50075. return this;
  50076. };
  50077. __decorate([
  50078. BABYLON.serialize()
  50079. ], PointLight.prototype, "shadowAngle", null);
  50080. return PointLight;
  50081. }(BABYLON.ShadowLight));
  50082. BABYLON.PointLight = PointLight;
  50083. })(BABYLON || (BABYLON = {}));
  50084. //# sourceMappingURL=babylon.pointLight.js.map
  50085. var BABYLON;
  50086. (function (BABYLON) {
  50087. /**
  50088. * A directional light is defined by a direction (what a surprise!).
  50089. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50090. * 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.
  50091. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50092. */
  50093. var DirectionalLight = /** @class */ (function (_super) {
  50094. __extends(DirectionalLight, _super);
  50095. /**
  50096. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50097. * The directional light is emitted from everywhere in the given direction.
  50098. * It can cast shawdows.
  50099. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50100. * @param name The friendly name of the light
  50101. * @param direction The direction of the light
  50102. * @param scene The scene the light belongs to
  50103. */
  50104. function DirectionalLight(name, direction, scene) {
  50105. var _this = _super.call(this, name, scene) || this;
  50106. _this._shadowFrustumSize = 0;
  50107. _this._shadowOrthoScale = 0.1;
  50108. /**
  50109. * Automatically compute the projection matrix to best fit (including all the casters)
  50110. * on each frame.
  50111. */
  50112. _this.autoUpdateExtends = true;
  50113. // Cache
  50114. _this._orthoLeft = Number.MAX_VALUE;
  50115. _this._orthoRight = Number.MIN_VALUE;
  50116. _this._orthoTop = Number.MIN_VALUE;
  50117. _this._orthoBottom = Number.MAX_VALUE;
  50118. _this.position = direction.scale(-1.0);
  50119. _this.direction = direction;
  50120. return _this;
  50121. }
  50122. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50123. /**
  50124. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50125. */
  50126. get: function () {
  50127. return this._shadowFrustumSize;
  50128. },
  50129. /**
  50130. * Specifies a fix frustum size for the shadow generation.
  50131. */
  50132. set: function (value) {
  50133. this._shadowFrustumSize = value;
  50134. this.forceProjectionMatrixCompute();
  50135. },
  50136. enumerable: true,
  50137. configurable: true
  50138. });
  50139. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50140. /**
  50141. * Gets the shadow projection scale against the optimal computed one.
  50142. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50143. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50144. */
  50145. get: function () {
  50146. return this._shadowOrthoScale;
  50147. },
  50148. /**
  50149. * Sets the shadow projection scale against the optimal computed one.
  50150. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50151. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50152. */
  50153. set: function (value) {
  50154. this._shadowOrthoScale = value;
  50155. this.forceProjectionMatrixCompute();
  50156. },
  50157. enumerable: true,
  50158. configurable: true
  50159. });
  50160. /**
  50161. * Returns the string "DirectionalLight".
  50162. * @return The class name
  50163. */
  50164. DirectionalLight.prototype.getClassName = function () {
  50165. return "DirectionalLight";
  50166. };
  50167. /**
  50168. * Returns the integer 1.
  50169. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50170. */
  50171. DirectionalLight.prototype.getTypeID = function () {
  50172. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50173. };
  50174. /**
  50175. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50176. * Returns the DirectionalLight Shadow projection matrix.
  50177. */
  50178. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50179. if (this.shadowFrustumSize > 0) {
  50180. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50181. }
  50182. else {
  50183. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50184. }
  50185. };
  50186. /**
  50187. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50188. * Returns the DirectionalLight Shadow projection matrix.
  50189. */
  50190. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50191. var activeCamera = this.getScene().activeCamera;
  50192. if (!activeCamera) {
  50193. return;
  50194. }
  50195. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50196. };
  50197. /**
  50198. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50199. * Returns the DirectionalLight Shadow projection matrix.
  50200. */
  50201. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50202. var activeCamera = this.getScene().activeCamera;
  50203. if (!activeCamera) {
  50204. return;
  50205. }
  50206. // Check extends
  50207. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50208. var tempVector3 = BABYLON.Vector3.Zero();
  50209. this._orthoLeft = Number.MAX_VALUE;
  50210. this._orthoRight = Number.MIN_VALUE;
  50211. this._orthoTop = Number.MIN_VALUE;
  50212. this._orthoBottom = Number.MAX_VALUE;
  50213. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50214. var mesh = renderList[meshIndex];
  50215. if (!mesh) {
  50216. continue;
  50217. }
  50218. var boundingInfo = mesh.getBoundingInfo();
  50219. var boundingBox = boundingInfo.boundingBox;
  50220. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50221. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50222. if (tempVector3.x < this._orthoLeft)
  50223. this._orthoLeft = tempVector3.x;
  50224. if (tempVector3.y < this._orthoBottom)
  50225. this._orthoBottom = tempVector3.y;
  50226. if (tempVector3.x > this._orthoRight)
  50227. this._orthoRight = tempVector3.x;
  50228. if (tempVector3.y > this._orthoTop)
  50229. this._orthoTop = tempVector3.y;
  50230. }
  50231. }
  50232. }
  50233. var xOffset = this._orthoRight - this._orthoLeft;
  50234. var yOffset = this._orthoTop - this._orthoBottom;
  50235. 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);
  50236. };
  50237. DirectionalLight.prototype._buildUniformLayout = function () {
  50238. this._uniformBuffer.addUniform("vLightData", 4);
  50239. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50240. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50241. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50242. this._uniformBuffer.addUniform("depthValues", 2);
  50243. this._uniformBuffer.create();
  50244. };
  50245. /**
  50246. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50247. * @param effect The effect to update
  50248. * @param lightIndex The index of the light in the effect to update
  50249. * @returns The directional light
  50250. */
  50251. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50252. if (this.computeTransformedInformation()) {
  50253. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50254. return this;
  50255. }
  50256. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50257. return this;
  50258. };
  50259. /**
  50260. * Gets the minZ used for shadow according to both the scene and the light.
  50261. *
  50262. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50263. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50264. * @param activeCamera The camera we are returning the min for
  50265. * @returns the depth min z
  50266. */
  50267. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50268. return 1;
  50269. };
  50270. /**
  50271. * Gets the maxZ used for shadow according to both the scene and the light.
  50272. *
  50273. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50274. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50275. * @param activeCamera The camera we are returning the max for
  50276. * @returns the depth max z
  50277. */
  50278. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50279. return 1;
  50280. };
  50281. __decorate([
  50282. BABYLON.serialize()
  50283. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50284. __decorate([
  50285. BABYLON.serialize()
  50286. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50287. __decorate([
  50288. BABYLON.serialize()
  50289. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50290. return DirectionalLight;
  50291. }(BABYLON.ShadowLight));
  50292. BABYLON.DirectionalLight = DirectionalLight;
  50293. })(BABYLON || (BABYLON = {}));
  50294. //# sourceMappingURL=babylon.directionalLight.js.map
  50295. var BABYLON;
  50296. (function (BABYLON) {
  50297. /**
  50298. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50299. * These values define a cone of light starting from the position, emitting toward the direction.
  50300. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50301. * and the exponent defines the speed of the decay of the light with distance (reach).
  50302. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50303. */
  50304. var SpotLight = /** @class */ (function (_super) {
  50305. __extends(SpotLight, _super);
  50306. /**
  50307. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50308. * It can cast shadows.
  50309. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50310. * @param name The light friendly name
  50311. * @param position The position of the spot light in the scene
  50312. * @param direction The direction of the light in the scene
  50313. * @param angle The cone angle of the light in Radians
  50314. * @param exponent The light decay speed with the distance from the emission spot
  50315. * @param scene The scene the lights belongs to
  50316. */
  50317. function SpotLight(name, position, direction, angle, exponent, scene) {
  50318. var _this = _super.call(this, name, scene) || this;
  50319. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50320. _this._projectionTextureLightNear = 1e-6;
  50321. _this._projectionTextureLightFar = 1000.0;
  50322. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50323. _this._projectionTextureViewLightDirty = true;
  50324. _this._projectionTextureProjectionLightDirty = true;
  50325. _this._projectionTextureDirty = true;
  50326. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50327. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50328. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50329. _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);
  50330. _this.position = position;
  50331. _this.direction = direction;
  50332. _this.angle = angle;
  50333. _this.exponent = exponent;
  50334. return _this;
  50335. }
  50336. Object.defineProperty(SpotLight.prototype, "angle", {
  50337. /**
  50338. * Gets the cone angle of the spot light in Radians.
  50339. */
  50340. get: function () {
  50341. return this._angle;
  50342. },
  50343. /**
  50344. * Sets the cone angle of the spot light in Radians.
  50345. */
  50346. set: function (value) {
  50347. this._angle = value;
  50348. this._projectionTextureProjectionLightDirty = true;
  50349. this.forceProjectionMatrixCompute();
  50350. },
  50351. enumerable: true,
  50352. configurable: true
  50353. });
  50354. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50355. /**
  50356. * Allows scaling the angle of the light for shadow generation only.
  50357. */
  50358. get: function () {
  50359. return this._shadowAngleScale;
  50360. },
  50361. /**
  50362. * Allows scaling the angle of the light for shadow generation only.
  50363. */
  50364. set: function (value) {
  50365. this._shadowAngleScale = value;
  50366. this.forceProjectionMatrixCompute();
  50367. },
  50368. enumerable: true,
  50369. configurable: true
  50370. });
  50371. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50372. /**
  50373. * Allows reading the projecton texture
  50374. */
  50375. get: function () {
  50376. return this._projectionTextureMatrix;
  50377. },
  50378. enumerable: true,
  50379. configurable: true
  50380. });
  50381. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50382. /**
  50383. * Gets the near clip of the Spotlight for texture projection.
  50384. */
  50385. get: function () {
  50386. return this._projectionTextureLightNear;
  50387. },
  50388. /**
  50389. * Sets the near clip of the Spotlight for texture projection.
  50390. */
  50391. set: function (value) {
  50392. this._projectionTextureLightNear = value;
  50393. this._projectionTextureProjectionLightDirty = true;
  50394. },
  50395. enumerable: true,
  50396. configurable: true
  50397. });
  50398. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50399. /**
  50400. * Gets the far clip of the Spotlight for texture projection.
  50401. */
  50402. get: function () {
  50403. return this._projectionTextureLightFar;
  50404. },
  50405. /**
  50406. * Sets the far clip of the Spotlight for texture projection.
  50407. */
  50408. set: function (value) {
  50409. this._projectionTextureLightFar = value;
  50410. this._projectionTextureProjectionLightDirty = true;
  50411. },
  50412. enumerable: true,
  50413. configurable: true
  50414. });
  50415. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50416. /**
  50417. * Gets the Up vector of the Spotlight for texture projection.
  50418. */
  50419. get: function () {
  50420. return this._projectionTextureUpDirection;
  50421. },
  50422. /**
  50423. * Sets the Up vector of the Spotlight for texture projection.
  50424. */
  50425. set: function (value) {
  50426. this._projectionTextureUpDirection = value;
  50427. this._projectionTextureProjectionLightDirty = true;
  50428. },
  50429. enumerable: true,
  50430. configurable: true
  50431. });
  50432. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50433. /**
  50434. * Gets the projection texture of the light.
  50435. */
  50436. get: function () {
  50437. return this._projectionTexture;
  50438. },
  50439. /**
  50440. * Sets the projection texture of the light.
  50441. */
  50442. set: function (value) {
  50443. this._projectionTexture = value;
  50444. this._projectionTextureDirty = true;
  50445. },
  50446. enumerable: true,
  50447. configurable: true
  50448. });
  50449. /**
  50450. * Returns the string "SpotLight".
  50451. * @returns the class name
  50452. */
  50453. SpotLight.prototype.getClassName = function () {
  50454. return "SpotLight";
  50455. };
  50456. /**
  50457. * Returns the integer 2.
  50458. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50459. */
  50460. SpotLight.prototype.getTypeID = function () {
  50461. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50462. };
  50463. /**
  50464. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50465. */
  50466. SpotLight.prototype._setDirection = function (value) {
  50467. _super.prototype._setDirection.call(this, value);
  50468. this._projectionTextureViewLightDirty = true;
  50469. };
  50470. /**
  50471. * Overrides the position setter to recompute the projection texture view light Matrix.
  50472. */
  50473. SpotLight.prototype._setPosition = function (value) {
  50474. _super.prototype._setPosition.call(this, value);
  50475. this._projectionTextureViewLightDirty = true;
  50476. };
  50477. /**
  50478. * 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.
  50479. * Returns the SpotLight.
  50480. */
  50481. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50482. var activeCamera = this.getScene().activeCamera;
  50483. if (!activeCamera) {
  50484. return;
  50485. }
  50486. this._shadowAngleScale = this._shadowAngleScale || 1;
  50487. var angle = this._shadowAngleScale * this._angle;
  50488. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50489. };
  50490. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50491. this._projectionTextureViewLightDirty = false;
  50492. this._projectionTextureDirty = true;
  50493. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50494. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50495. };
  50496. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50497. this._projectionTextureProjectionLightDirty = false;
  50498. this._projectionTextureDirty = true;
  50499. var light_far = this.projectionTextureLightFar;
  50500. var light_near = this.projectionTextureLightNear;
  50501. var P = light_far / (light_far - light_near);
  50502. var Q = -P * light_near;
  50503. var S = 1.0 / Math.tan(this._angle / 2.0);
  50504. var A = 1.0;
  50505. 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);
  50506. };
  50507. /**
  50508. * Main function for light texture projection matrix computing.
  50509. */
  50510. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50511. this._projectionTextureDirty = false;
  50512. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50513. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50514. };
  50515. SpotLight.prototype._buildUniformLayout = function () {
  50516. this._uniformBuffer.addUniform("vLightData", 4);
  50517. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50518. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50519. this._uniformBuffer.addUniform("vLightDirection", 3);
  50520. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50521. this._uniformBuffer.addUniform("depthValues", 2);
  50522. this._uniformBuffer.create();
  50523. };
  50524. /**
  50525. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50526. * @param effect The effect to update
  50527. * @param lightIndex The index of the light in the effect to update
  50528. * @returns The spot light
  50529. */
  50530. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50531. var normalizeDirection;
  50532. if (this.computeTransformedInformation()) {
  50533. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50534. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50535. }
  50536. else {
  50537. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50538. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50539. }
  50540. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50541. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50542. if (this._projectionTextureViewLightDirty) {
  50543. this._computeProjectionTextureViewLightMatrix();
  50544. }
  50545. if (this._projectionTextureProjectionLightDirty) {
  50546. this._computeProjectionTextureProjectionLightMatrix();
  50547. }
  50548. if (this._projectionTextureDirty) {
  50549. this._computeProjectionTextureMatrix();
  50550. }
  50551. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50552. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50553. }
  50554. return this;
  50555. };
  50556. /**
  50557. * Disposes the light and the associated resources.
  50558. */
  50559. SpotLight.prototype.dispose = function () {
  50560. _super.prototype.dispose.call(this);
  50561. if (this._projectionTexture) {
  50562. this._projectionTexture.dispose();
  50563. }
  50564. };
  50565. __decorate([
  50566. BABYLON.serialize()
  50567. ], SpotLight.prototype, "angle", null);
  50568. __decorate([
  50569. BABYLON.serialize()
  50570. ], SpotLight.prototype, "shadowAngleScale", null);
  50571. __decorate([
  50572. BABYLON.serialize()
  50573. ], SpotLight.prototype, "exponent", void 0);
  50574. __decorate([
  50575. BABYLON.serialize()
  50576. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50577. __decorate([
  50578. BABYLON.serialize()
  50579. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50580. __decorate([
  50581. BABYLON.serialize()
  50582. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50583. __decorate([
  50584. BABYLON.serializeAsTexture("projectedLightTexture")
  50585. ], SpotLight.prototype, "_projectionTexture", void 0);
  50586. return SpotLight;
  50587. }(BABYLON.ShadowLight));
  50588. BABYLON.SpotLight = SpotLight;
  50589. })(BABYLON || (BABYLON = {}));
  50590. //# sourceMappingURL=babylon.spotLight.js.map
  50591. var BABYLON;
  50592. (function (BABYLON) {
  50593. /**
  50594. * Class used to override all child animations of a given target
  50595. */
  50596. var AnimationPropertiesOverride = /** @class */ (function () {
  50597. function AnimationPropertiesOverride() {
  50598. /**
  50599. * Gets or sets a value indicating if animation blending must be used
  50600. */
  50601. this.enableBlending = false;
  50602. /**
  50603. * Gets or sets the blending speed to use when enableBlending is true
  50604. */
  50605. this.blendingSpeed = 0.01;
  50606. /**
  50607. * Gets or sets the default loop mode to use
  50608. */
  50609. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50610. }
  50611. return AnimationPropertiesOverride;
  50612. }());
  50613. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50614. })(BABYLON || (BABYLON = {}));
  50615. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50616. var BABYLON;
  50617. (function (BABYLON) {
  50618. /**
  50619. * Represents the range of an animation
  50620. */
  50621. var AnimationRange = /** @class */ (function () {
  50622. /**
  50623. * Initializes the range of an animation
  50624. * @param name The name of the animation range
  50625. * @param from The starting frame of the animation
  50626. * @param to The ending frame of the animation
  50627. */
  50628. function AnimationRange(
  50629. /**The name of the animation range**/
  50630. name,
  50631. /**The starting frame of the animation */
  50632. from,
  50633. /**The ending frame of the animation*/
  50634. to) {
  50635. this.name = name;
  50636. this.from = from;
  50637. this.to = to;
  50638. }
  50639. /**
  50640. * Makes a copy of the animation range
  50641. * @returns A copy of the animation range
  50642. */
  50643. AnimationRange.prototype.clone = function () {
  50644. return new AnimationRange(this.name, this.from, this.to);
  50645. };
  50646. return AnimationRange;
  50647. }());
  50648. BABYLON.AnimationRange = AnimationRange;
  50649. /**
  50650. * Composed of a frame, and an action function
  50651. */
  50652. var AnimationEvent = /** @class */ (function () {
  50653. /**
  50654. * Initializes the animation event
  50655. * @param frame The frame for which the event is triggered
  50656. * @param action The event to perform when triggered
  50657. * @param onlyOnce Specifies if the event should be triggered only once
  50658. */
  50659. function AnimationEvent(
  50660. /** The frame for which the event is triggered **/
  50661. frame,
  50662. /** The event to perform when triggered **/
  50663. action,
  50664. /** Specifies if the event should be triggered only once**/
  50665. onlyOnce) {
  50666. this.frame = frame;
  50667. this.action = action;
  50668. this.onlyOnce = onlyOnce;
  50669. /**
  50670. * Specifies if the animation event is done
  50671. */
  50672. this.isDone = false;
  50673. }
  50674. /** @hidden */
  50675. AnimationEvent.prototype._clone = function () {
  50676. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50677. };
  50678. return AnimationEvent;
  50679. }());
  50680. BABYLON.AnimationEvent = AnimationEvent;
  50681. /**
  50682. * A cursor which tracks a point on a path
  50683. */
  50684. var PathCursor = /** @class */ (function () {
  50685. /**
  50686. * Initializes the path cursor
  50687. * @param path The path to track
  50688. */
  50689. function PathCursor(path) {
  50690. this.path = path;
  50691. /**
  50692. * Stores path cursor callbacks for when an onchange event is triggered
  50693. */
  50694. this._onchange = new Array();
  50695. /**
  50696. * The value of the path cursor
  50697. */
  50698. this.value = 0;
  50699. /**
  50700. * The animation array of the path cursor
  50701. */
  50702. this.animations = new Array();
  50703. }
  50704. /**
  50705. * Gets the cursor point on the path
  50706. * @returns A point on the path cursor at the cursor location
  50707. */
  50708. PathCursor.prototype.getPoint = function () {
  50709. var point = this.path.getPointAtLengthPosition(this.value);
  50710. return new BABYLON.Vector3(point.x, 0, point.y);
  50711. };
  50712. /**
  50713. * Moves the cursor ahead by the step amount
  50714. * @param step The amount to move the cursor forward
  50715. * @returns This path cursor
  50716. */
  50717. PathCursor.prototype.moveAhead = function (step) {
  50718. if (step === void 0) { step = 0.002; }
  50719. this.move(step);
  50720. return this;
  50721. };
  50722. /**
  50723. * Moves the cursor behind by the step amount
  50724. * @param step The amount to move the cursor back
  50725. * @returns This path cursor
  50726. */
  50727. PathCursor.prototype.moveBack = function (step) {
  50728. if (step === void 0) { step = 0.002; }
  50729. this.move(-step);
  50730. return this;
  50731. };
  50732. /**
  50733. * Moves the cursor by the step amount
  50734. * If the step amount is greater than one, an exception is thrown
  50735. * @param step The amount to move the cursor
  50736. * @returns This path cursor
  50737. */
  50738. PathCursor.prototype.move = function (step) {
  50739. if (Math.abs(step) > 1) {
  50740. throw "step size should be less than 1.";
  50741. }
  50742. this.value += step;
  50743. this.ensureLimits();
  50744. this.raiseOnChange();
  50745. return this;
  50746. };
  50747. /**
  50748. * Ensures that the value is limited between zero and one
  50749. * @returns This path cursor
  50750. */
  50751. PathCursor.prototype.ensureLimits = function () {
  50752. while (this.value > 1) {
  50753. this.value -= 1;
  50754. }
  50755. while (this.value < 0) {
  50756. this.value += 1;
  50757. }
  50758. return this;
  50759. };
  50760. /**
  50761. * Runs onchange callbacks on change (used by the animation engine)
  50762. * @returns This path cursor
  50763. */
  50764. PathCursor.prototype.raiseOnChange = function () {
  50765. var _this = this;
  50766. this._onchange.forEach(function (f) { return f(_this); });
  50767. return this;
  50768. };
  50769. /**
  50770. * Executes a function on change
  50771. * @param f A path cursor onchange callback
  50772. * @returns This path cursor
  50773. */
  50774. PathCursor.prototype.onchange = function (f) {
  50775. this._onchange.push(f);
  50776. return this;
  50777. };
  50778. return PathCursor;
  50779. }());
  50780. BABYLON.PathCursor = PathCursor;
  50781. /**
  50782. * Enum for the animation key frame interpolation type
  50783. */
  50784. var AnimationKeyInterpolation;
  50785. (function (AnimationKeyInterpolation) {
  50786. /**
  50787. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50788. */
  50789. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50790. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50791. /**
  50792. * Class used to store any kind of animation
  50793. */
  50794. var Animation = /** @class */ (function () {
  50795. /**
  50796. * Initializes the animation
  50797. * @param name Name of the animation
  50798. * @param targetProperty Property to animate
  50799. * @param framePerSecond The frames per second of the animation
  50800. * @param dataType The data type of the animation
  50801. * @param loopMode The loop mode of the animation
  50802. * @param enableBlendings Specifies if blending should be enabled
  50803. */
  50804. function Animation(
  50805. /**Name of the animation */
  50806. name,
  50807. /**Property to animate */
  50808. targetProperty,
  50809. /**The frames per second of the animation */
  50810. framePerSecond,
  50811. /**The data type of the animation */
  50812. dataType,
  50813. /**The loop mode of the animation */
  50814. loopMode,
  50815. /**Specifies if blending should be enabled */
  50816. enableBlending) {
  50817. this.name = name;
  50818. this.targetProperty = targetProperty;
  50819. this.framePerSecond = framePerSecond;
  50820. this.dataType = dataType;
  50821. this.loopMode = loopMode;
  50822. this.enableBlending = enableBlending;
  50823. /**
  50824. * @hidden Internal use only
  50825. */
  50826. this._runtimeAnimations = new Array();
  50827. /**
  50828. * The set of event that will be linked to this animation
  50829. */
  50830. this._events = new Array();
  50831. /**
  50832. * Stores the blending speed of the animation
  50833. */
  50834. this.blendingSpeed = 0.01;
  50835. /**
  50836. * Stores the animation ranges for the animation
  50837. */
  50838. this._ranges = {};
  50839. this.targetPropertyPath = targetProperty.split(".");
  50840. this.dataType = dataType;
  50841. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50842. }
  50843. /**
  50844. * @hidden Internal use
  50845. */
  50846. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50847. var dataType = undefined;
  50848. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50849. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50850. }
  50851. else if (from instanceof BABYLON.Quaternion) {
  50852. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50853. }
  50854. else if (from instanceof BABYLON.Vector3) {
  50855. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50856. }
  50857. else if (from instanceof BABYLON.Vector2) {
  50858. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50859. }
  50860. else if (from instanceof BABYLON.Color3) {
  50861. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50862. }
  50863. else if (from instanceof BABYLON.Size) {
  50864. dataType = Animation.ANIMATIONTYPE_SIZE;
  50865. }
  50866. if (dataType == undefined) {
  50867. return null;
  50868. }
  50869. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50870. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50871. animation.setKeys(keys);
  50872. if (easingFunction !== undefined) {
  50873. animation.setEasingFunction(easingFunction);
  50874. }
  50875. return animation;
  50876. };
  50877. /**
  50878. * Sets up an animation
  50879. * @param property The property to animate
  50880. * @param animationType The animation type to apply
  50881. * @param framePerSecond The frames per second of the animation
  50882. * @param easingFunction The easing function used in the animation
  50883. * @returns The created animation
  50884. */
  50885. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50886. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50887. animation.setEasingFunction(easingFunction);
  50888. return animation;
  50889. };
  50890. /**
  50891. * Create and start an animation on a node
  50892. * @param name defines the name of the global animation that will be run on all nodes
  50893. * @param node defines the root node where the animation will take place
  50894. * @param targetProperty defines property to animate
  50895. * @param framePerSecond defines the number of frame per second yo use
  50896. * @param totalFrame defines the number of frames in total
  50897. * @param from defines the initial value
  50898. * @param to defines the final value
  50899. * @param loopMode defines which loop mode you want to use (off by default)
  50900. * @param easingFunction defines the easing function to use (linear by default)
  50901. * @param onAnimationEnd defines the callback to call when animation end
  50902. * @returns the animatable created for this animation
  50903. */
  50904. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50905. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50906. if (!animation) {
  50907. return null;
  50908. }
  50909. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50910. };
  50911. /**
  50912. * Create and start an animation on a node and its descendants
  50913. * @param name defines the name of the global animation that will be run on all nodes
  50914. * @param node defines the root node where the animation will take place
  50915. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50916. * @param targetProperty defines property to animate
  50917. * @param framePerSecond defines the number of frame per second to use
  50918. * @param totalFrame defines the number of frames in total
  50919. * @param from defines the initial value
  50920. * @param to defines the final value
  50921. * @param loopMode defines which loop mode you want to use (off by default)
  50922. * @param easingFunction defines the easing function to use (linear by default)
  50923. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50924. * @returns the list of animatables created for all nodes
  50925. * @example https://www.babylonjs-playground.com/#MH0VLI
  50926. */
  50927. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50928. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50929. if (!animation) {
  50930. return null;
  50931. }
  50932. var scene = node.getScene();
  50933. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50934. };
  50935. /**
  50936. * Creates a new animation, merges it with the existing animations and starts it
  50937. * @param name Name of the animation
  50938. * @param node Node which contains the scene that begins the animations
  50939. * @param targetProperty Specifies which property to animate
  50940. * @param framePerSecond The frames per second of the animation
  50941. * @param totalFrame The total number of frames
  50942. * @param from The frame at the beginning of the animation
  50943. * @param to The frame at the end of the animation
  50944. * @param loopMode Specifies the loop mode of the animation
  50945. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50946. * @param onAnimationEnd Callback to run once the animation is complete
  50947. * @returns Nullable animation
  50948. */
  50949. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50950. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50951. if (!animation) {
  50952. return null;
  50953. }
  50954. node.animations.push(animation);
  50955. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50956. };
  50957. /**
  50958. * Transition property of an host to the target Value
  50959. * @param property The property to transition
  50960. * @param targetValue The target Value of the property
  50961. * @param host The object where the property to animate belongs
  50962. * @param scene Scene used to run the animation
  50963. * @param frameRate Framerate (in frame/s) to use
  50964. * @param transition The transition type we want to use
  50965. * @param duration The duration of the animation, in milliseconds
  50966. * @param onAnimationEnd Callback trigger at the end of the animation
  50967. * @returns Nullable animation
  50968. */
  50969. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50970. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50971. if (duration <= 0) {
  50972. host[property] = targetValue;
  50973. if (onAnimationEnd) {
  50974. onAnimationEnd();
  50975. }
  50976. return null;
  50977. }
  50978. var endFrame = frameRate * (duration / 1000);
  50979. transition.setKeys([{
  50980. frame: 0,
  50981. value: host[property].clone ? host[property].clone() : host[property]
  50982. },
  50983. {
  50984. frame: endFrame,
  50985. value: targetValue
  50986. }]);
  50987. if (!host.animations) {
  50988. host.animations = [];
  50989. }
  50990. host.animations.push(transition);
  50991. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50992. animation.onAnimationEnd = onAnimationEnd;
  50993. return animation;
  50994. };
  50995. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50996. /**
  50997. * Return the array of runtime animations currently using this animation
  50998. */
  50999. get: function () {
  51000. return this._runtimeAnimations;
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51006. /**
  51007. * Specifies if any of the runtime animations are currently running
  51008. */
  51009. get: function () {
  51010. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51011. var runtimeAnimation = _a[_i];
  51012. if (!runtimeAnimation.isStopped) {
  51013. return true;
  51014. }
  51015. }
  51016. return false;
  51017. },
  51018. enumerable: true,
  51019. configurable: true
  51020. });
  51021. // Methods
  51022. /**
  51023. * Converts the animation to a string
  51024. * @param fullDetails support for multiple levels of logging within scene loading
  51025. * @returns String form of the animation
  51026. */
  51027. Animation.prototype.toString = function (fullDetails) {
  51028. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51029. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51030. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51031. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51032. if (fullDetails) {
  51033. ret += ", Ranges: {";
  51034. var first = true;
  51035. for (var name in this._ranges) {
  51036. if (first) {
  51037. ret += ", ";
  51038. first = false;
  51039. }
  51040. ret += name;
  51041. }
  51042. ret += "}";
  51043. }
  51044. return ret;
  51045. };
  51046. /**
  51047. * Add an event to this animation
  51048. * @param event Event to add
  51049. */
  51050. Animation.prototype.addEvent = function (event) {
  51051. this._events.push(event);
  51052. };
  51053. /**
  51054. * Remove all events found at the given frame
  51055. * @param frame The frame to remove events from
  51056. */
  51057. Animation.prototype.removeEvents = function (frame) {
  51058. for (var index = 0; index < this._events.length; index++) {
  51059. if (this._events[index].frame === frame) {
  51060. this._events.splice(index, 1);
  51061. index--;
  51062. }
  51063. }
  51064. };
  51065. /**
  51066. * Retrieves all the events from the animation
  51067. * @returns Events from the animation
  51068. */
  51069. Animation.prototype.getEvents = function () {
  51070. return this._events;
  51071. };
  51072. /**
  51073. * Creates an animation range
  51074. * @param name Name of the animation range
  51075. * @param from Starting frame of the animation range
  51076. * @param to Ending frame of the animation
  51077. */
  51078. Animation.prototype.createRange = function (name, from, to) {
  51079. // check name not already in use; could happen for bones after serialized
  51080. if (!this._ranges[name]) {
  51081. this._ranges[name] = new AnimationRange(name, from, to);
  51082. }
  51083. };
  51084. /**
  51085. * Deletes an animation range by name
  51086. * @param name Name of the animation range to delete
  51087. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51088. */
  51089. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51090. if (deleteFrames === void 0) { deleteFrames = true; }
  51091. var range = this._ranges[name];
  51092. if (!range) {
  51093. return;
  51094. }
  51095. if (deleteFrames) {
  51096. var from = range.from;
  51097. var to = range.to;
  51098. // this loop MUST go high to low for multiple splices to work
  51099. for (var key = this._keys.length - 1; key >= 0; key--) {
  51100. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51101. this._keys.splice(key, 1);
  51102. }
  51103. }
  51104. }
  51105. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51106. };
  51107. /**
  51108. * Gets the animation range by name, or null if not defined
  51109. * @param name Name of the animation range
  51110. * @returns Nullable animation range
  51111. */
  51112. Animation.prototype.getRange = function (name) {
  51113. return this._ranges[name];
  51114. };
  51115. /**
  51116. * Gets the key frames from the animation
  51117. * @returns The key frames of the animation
  51118. */
  51119. Animation.prototype.getKeys = function () {
  51120. return this._keys;
  51121. };
  51122. /**
  51123. * Gets the highest frame rate of the animation
  51124. * @returns Highest frame rate of the animation
  51125. */
  51126. Animation.prototype.getHighestFrame = function () {
  51127. var ret = 0;
  51128. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51129. if (ret < this._keys[key].frame) {
  51130. ret = this._keys[key].frame;
  51131. }
  51132. }
  51133. return ret;
  51134. };
  51135. /**
  51136. * Gets the easing function of the animation
  51137. * @returns Easing function of the animation
  51138. */
  51139. Animation.prototype.getEasingFunction = function () {
  51140. return this._easingFunction;
  51141. };
  51142. /**
  51143. * Sets the easing function of the animation
  51144. * @param easingFunction A custom mathematical formula for animation
  51145. */
  51146. Animation.prototype.setEasingFunction = function (easingFunction) {
  51147. this._easingFunction = easingFunction;
  51148. };
  51149. /**
  51150. * Interpolates a scalar linearly
  51151. * @param startValue Start value of the animation curve
  51152. * @param endValue End value of the animation curve
  51153. * @param gradient Scalar amount to interpolate
  51154. * @returns Interpolated scalar value
  51155. */
  51156. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51157. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51158. };
  51159. /**
  51160. * Interpolates a scalar cubically
  51161. * @param startValue Start value of the animation curve
  51162. * @param outTangent End tangent of the animation
  51163. * @param endValue End value of the animation curve
  51164. * @param inTangent Start tangent of the animation curve
  51165. * @param gradient Scalar amount to interpolate
  51166. * @returns Interpolated scalar value
  51167. */
  51168. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51169. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51170. };
  51171. /**
  51172. * Interpolates a quaternion using a spherical linear interpolation
  51173. * @param startValue Start value of the animation curve
  51174. * @param endValue End value of the animation curve
  51175. * @param gradient Scalar amount to interpolate
  51176. * @returns Interpolated quaternion value
  51177. */
  51178. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51179. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51180. };
  51181. /**
  51182. * Interpolates a quaternion cubically
  51183. * @param startValue Start value of the animation curve
  51184. * @param outTangent End tangent of the animation curve
  51185. * @param endValue End value of the animation curve
  51186. * @param inTangent Start tangent of the animation curve
  51187. * @param gradient Scalar amount to interpolate
  51188. * @returns Interpolated quaternion value
  51189. */
  51190. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51191. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51192. };
  51193. /**
  51194. * Interpolates a Vector3 linearl
  51195. * @param startValue Start value of the animation curve
  51196. * @param endValue End value of the animation curve
  51197. * @param gradient Scalar amount to interpolate
  51198. * @returns Interpolated scalar value
  51199. */
  51200. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51201. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51202. };
  51203. /**
  51204. * Interpolates a Vector3 cubically
  51205. * @param startValue Start value of the animation curve
  51206. * @param outTangent End tangent of the animation
  51207. * @param endValue End value of the animation curve
  51208. * @param inTangent Start tangent of the animation curve
  51209. * @param gradient Scalar amount to interpolate
  51210. * @returns InterpolatedVector3 value
  51211. */
  51212. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51213. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51214. };
  51215. /**
  51216. * Interpolates a Vector2 linearly
  51217. * @param startValue Start value of the animation curve
  51218. * @param endValue End value of the animation curve
  51219. * @param gradient Scalar amount to interpolate
  51220. * @returns Interpolated Vector2 value
  51221. */
  51222. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51223. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51224. };
  51225. /**
  51226. * Interpolates a Vector2 cubically
  51227. * @param startValue Start value of the animation curve
  51228. * @param outTangent End tangent of the animation
  51229. * @param endValue End value of the animation curve
  51230. * @param inTangent Start tangent of the animation curve
  51231. * @param gradient Scalar amount to interpolate
  51232. * @returns Interpolated Vector2 value
  51233. */
  51234. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51235. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51236. };
  51237. /**
  51238. * Interpolates a size linearly
  51239. * @param startValue Start value of the animation curve
  51240. * @param endValue End value of the animation curve
  51241. * @param gradient Scalar amount to interpolate
  51242. * @returns Interpolated Size value
  51243. */
  51244. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51245. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51246. };
  51247. /**
  51248. * Interpolates a Color3 linearly
  51249. * @param startValue Start value of the animation curve
  51250. * @param endValue End value of the animation curve
  51251. * @param gradient Scalar amount to interpolate
  51252. * @returns Interpolated Color3 value
  51253. */
  51254. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51255. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51256. };
  51257. /**
  51258. * @hidden Internal use only
  51259. */
  51260. Animation.prototype._getKeyValue = function (value) {
  51261. if (typeof value === "function") {
  51262. return value();
  51263. }
  51264. return value;
  51265. };
  51266. /**
  51267. * @hidden Internal use only
  51268. */
  51269. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51270. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51271. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51272. }
  51273. var keys = this.getKeys();
  51274. // Try to get a hash to find the right key
  51275. 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));
  51276. if (keys[startKeyIndex].frame >= currentFrame) {
  51277. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51278. startKeyIndex--;
  51279. }
  51280. }
  51281. for (var key = startKeyIndex; key < keys.length; key++) {
  51282. var endKey = keys[key + 1];
  51283. if (endKey.frame >= currentFrame) {
  51284. var startKey = keys[key];
  51285. var startValue = this._getKeyValue(startKey.value);
  51286. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51287. return startValue;
  51288. }
  51289. var endValue = this._getKeyValue(endKey.value);
  51290. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51291. var frameDelta = endKey.frame - startKey.frame;
  51292. // gradient : percent of currentFrame between the frame inf and the frame sup
  51293. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51294. // check for easingFunction and correction of gradient
  51295. var easingFunction = this.getEasingFunction();
  51296. if (easingFunction != null) {
  51297. gradient = easingFunction.ease(gradient);
  51298. }
  51299. switch (this.dataType) {
  51300. // Float
  51301. case Animation.ANIMATIONTYPE_FLOAT:
  51302. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51303. switch (loopMode) {
  51304. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51305. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51306. return floatValue;
  51307. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51308. return offsetValue * repeatCount + floatValue;
  51309. }
  51310. break;
  51311. // Quaternion
  51312. case Animation.ANIMATIONTYPE_QUATERNION:
  51313. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51314. switch (loopMode) {
  51315. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51316. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51317. return quatValue;
  51318. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51319. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51320. }
  51321. return quatValue;
  51322. // Vector3
  51323. case Animation.ANIMATIONTYPE_VECTOR3:
  51324. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51325. switch (loopMode) {
  51326. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51327. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51328. return vec3Value;
  51329. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51330. return vec3Value.add(offsetValue.scale(repeatCount));
  51331. }
  51332. // Vector2
  51333. case Animation.ANIMATIONTYPE_VECTOR2:
  51334. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51335. switch (loopMode) {
  51336. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51337. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51338. return vec2Value;
  51339. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51340. return vec2Value.add(offsetValue.scale(repeatCount));
  51341. }
  51342. // Size
  51343. case Animation.ANIMATIONTYPE_SIZE:
  51344. switch (loopMode) {
  51345. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51346. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51347. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51348. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51349. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51350. }
  51351. // Color3
  51352. case Animation.ANIMATIONTYPE_COLOR3:
  51353. switch (loopMode) {
  51354. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51355. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51356. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51357. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51358. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51359. }
  51360. // Matrix
  51361. case Animation.ANIMATIONTYPE_MATRIX:
  51362. switch (loopMode) {
  51363. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51364. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51365. if (Animation.AllowMatricesInterpolation) {
  51366. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51367. }
  51368. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51369. return startValue;
  51370. }
  51371. default:
  51372. break;
  51373. }
  51374. break;
  51375. }
  51376. }
  51377. return this._getKeyValue(keys[keys.length - 1].value);
  51378. };
  51379. /**
  51380. * Defines the function to use to interpolate matrices
  51381. * @param startValue defines the start matrix
  51382. * @param endValue defines the end matrix
  51383. * @param gradient defines the gradient between both matrices
  51384. * @param result defines an optional target matrix where to store the interpolation
  51385. * @returns the interpolated matrix
  51386. */
  51387. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51388. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51389. if (result) {
  51390. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51391. return result;
  51392. }
  51393. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51394. }
  51395. if (result) {
  51396. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51397. return result;
  51398. }
  51399. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51400. };
  51401. /**
  51402. * Makes a copy of the animation
  51403. * @returns Cloned animation
  51404. */
  51405. Animation.prototype.clone = function () {
  51406. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51407. clone.enableBlending = this.enableBlending;
  51408. clone.blendingSpeed = this.blendingSpeed;
  51409. if (this._keys) {
  51410. clone.setKeys(this._keys);
  51411. }
  51412. if (this._ranges) {
  51413. clone._ranges = {};
  51414. for (var name in this._ranges) {
  51415. var range = this._ranges[name];
  51416. if (!range) {
  51417. continue;
  51418. }
  51419. clone._ranges[name] = range.clone();
  51420. }
  51421. }
  51422. return clone;
  51423. };
  51424. /**
  51425. * Sets the key frames of the animation
  51426. * @param values The animation key frames to set
  51427. */
  51428. Animation.prototype.setKeys = function (values) {
  51429. this._keys = values.slice(0);
  51430. };
  51431. /**
  51432. * Serializes the animation to an object
  51433. * @returns Serialized object
  51434. */
  51435. Animation.prototype.serialize = function () {
  51436. var serializationObject = {};
  51437. serializationObject.name = this.name;
  51438. serializationObject.property = this.targetProperty;
  51439. serializationObject.framePerSecond = this.framePerSecond;
  51440. serializationObject.dataType = this.dataType;
  51441. serializationObject.loopBehavior = this.loopMode;
  51442. serializationObject.enableBlending = this.enableBlending;
  51443. serializationObject.blendingSpeed = this.blendingSpeed;
  51444. var dataType = this.dataType;
  51445. serializationObject.keys = [];
  51446. var keys = this.getKeys();
  51447. for (var index = 0; index < keys.length; index++) {
  51448. var animationKey = keys[index];
  51449. var key = {};
  51450. key.frame = animationKey.frame;
  51451. switch (dataType) {
  51452. case Animation.ANIMATIONTYPE_FLOAT:
  51453. key.values = [animationKey.value];
  51454. break;
  51455. case Animation.ANIMATIONTYPE_QUATERNION:
  51456. case Animation.ANIMATIONTYPE_MATRIX:
  51457. case Animation.ANIMATIONTYPE_VECTOR3:
  51458. case Animation.ANIMATIONTYPE_COLOR3:
  51459. key.values = animationKey.value.asArray();
  51460. break;
  51461. }
  51462. serializationObject.keys.push(key);
  51463. }
  51464. serializationObject.ranges = [];
  51465. for (var name in this._ranges) {
  51466. var source = this._ranges[name];
  51467. if (!source) {
  51468. continue;
  51469. }
  51470. var range = {};
  51471. range.name = name;
  51472. range.from = source.from;
  51473. range.to = source.to;
  51474. serializationObject.ranges.push(range);
  51475. }
  51476. return serializationObject;
  51477. };
  51478. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51479. /**
  51480. * Get the float animation type
  51481. */
  51482. get: function () {
  51483. return Animation._ANIMATIONTYPE_FLOAT;
  51484. },
  51485. enumerable: true,
  51486. configurable: true
  51487. });
  51488. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51489. /**
  51490. * Get the Vector3 animation type
  51491. */
  51492. get: function () {
  51493. return Animation._ANIMATIONTYPE_VECTOR3;
  51494. },
  51495. enumerable: true,
  51496. configurable: true
  51497. });
  51498. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51499. /**
  51500. * Get the Vectpr2 animation type
  51501. */
  51502. get: function () {
  51503. return Animation._ANIMATIONTYPE_VECTOR2;
  51504. },
  51505. enumerable: true,
  51506. configurable: true
  51507. });
  51508. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51509. /**
  51510. * Get the Size animation type
  51511. */
  51512. get: function () {
  51513. return Animation._ANIMATIONTYPE_SIZE;
  51514. },
  51515. enumerable: true,
  51516. configurable: true
  51517. });
  51518. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51519. /**
  51520. * Get the Quaternion animation type
  51521. */
  51522. get: function () {
  51523. return Animation._ANIMATIONTYPE_QUATERNION;
  51524. },
  51525. enumerable: true,
  51526. configurable: true
  51527. });
  51528. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51529. /**
  51530. * Get the Matrix animation type
  51531. */
  51532. get: function () {
  51533. return Animation._ANIMATIONTYPE_MATRIX;
  51534. },
  51535. enumerable: true,
  51536. configurable: true
  51537. });
  51538. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51539. /**
  51540. * Get the Color3 animation type
  51541. */
  51542. get: function () {
  51543. return Animation._ANIMATIONTYPE_COLOR3;
  51544. },
  51545. enumerable: true,
  51546. configurable: true
  51547. });
  51548. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51549. /**
  51550. * Get the Relative Loop Mode
  51551. */
  51552. get: function () {
  51553. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51554. },
  51555. enumerable: true,
  51556. configurable: true
  51557. });
  51558. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51559. /**
  51560. * Get the Cycle Loop Mode
  51561. */
  51562. get: function () {
  51563. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51564. },
  51565. enumerable: true,
  51566. configurable: true
  51567. });
  51568. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51569. /**
  51570. * Get the Constant Loop Mode
  51571. */
  51572. get: function () {
  51573. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51574. },
  51575. enumerable: true,
  51576. configurable: true
  51577. });
  51578. /** @hidden */
  51579. Animation._UniversalLerp = function (left, right, amount) {
  51580. var constructor = left.constructor;
  51581. if (constructor.Lerp) { // Lerp supported
  51582. return constructor.Lerp(left, right, amount);
  51583. }
  51584. else if (constructor.Slerp) { // Slerp supported
  51585. return constructor.Slerp(left, right, amount);
  51586. }
  51587. else if (left.toFixed) { // Number
  51588. return left * (1.0 - amount) + amount * right;
  51589. }
  51590. else { // Blending not supported
  51591. return right;
  51592. }
  51593. };
  51594. /**
  51595. * Parses an animation object and creates an animation
  51596. * @param parsedAnimation Parsed animation object
  51597. * @returns Animation object
  51598. */
  51599. Animation.Parse = function (parsedAnimation) {
  51600. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51601. var dataType = parsedAnimation.dataType;
  51602. var keys = [];
  51603. var data;
  51604. var index;
  51605. if (parsedAnimation.enableBlending) {
  51606. animation.enableBlending = parsedAnimation.enableBlending;
  51607. }
  51608. if (parsedAnimation.blendingSpeed) {
  51609. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51610. }
  51611. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51612. var key = parsedAnimation.keys[index];
  51613. var inTangent;
  51614. var outTangent;
  51615. switch (dataType) {
  51616. case Animation.ANIMATIONTYPE_FLOAT:
  51617. data = key.values[0];
  51618. if (key.values.length >= 1) {
  51619. inTangent = key.values[1];
  51620. }
  51621. if (key.values.length >= 2) {
  51622. outTangent = key.values[2];
  51623. }
  51624. break;
  51625. case Animation.ANIMATIONTYPE_QUATERNION:
  51626. data = BABYLON.Quaternion.FromArray(key.values);
  51627. if (key.values.length >= 8) {
  51628. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51629. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51630. inTangent = _inTangent;
  51631. }
  51632. }
  51633. if (key.values.length >= 12) {
  51634. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51635. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51636. outTangent = _outTangent;
  51637. }
  51638. }
  51639. break;
  51640. case Animation.ANIMATIONTYPE_MATRIX:
  51641. data = BABYLON.Matrix.FromArray(key.values);
  51642. break;
  51643. case Animation.ANIMATIONTYPE_COLOR3:
  51644. data = BABYLON.Color3.FromArray(key.values);
  51645. break;
  51646. case Animation.ANIMATIONTYPE_VECTOR3:
  51647. default:
  51648. data = BABYLON.Vector3.FromArray(key.values);
  51649. break;
  51650. }
  51651. var keyData = {};
  51652. keyData.frame = key.frame;
  51653. keyData.value = data;
  51654. if (inTangent != undefined) {
  51655. keyData.inTangent = inTangent;
  51656. }
  51657. if (outTangent != undefined) {
  51658. keyData.outTangent = outTangent;
  51659. }
  51660. keys.push(keyData);
  51661. }
  51662. animation.setKeys(keys);
  51663. if (parsedAnimation.ranges) {
  51664. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51665. data = parsedAnimation.ranges[index];
  51666. animation.createRange(data.name, data.from, data.to);
  51667. }
  51668. }
  51669. return animation;
  51670. };
  51671. /**
  51672. * Appends the serialized animations from the source animations
  51673. * @param source Source containing the animations
  51674. * @param destination Target to store the animations
  51675. */
  51676. Animation.AppendSerializedAnimations = function (source, destination) {
  51677. if (source.animations) {
  51678. destination.animations = [];
  51679. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51680. var animation = source.animations[animationIndex];
  51681. destination.animations.push(animation.serialize());
  51682. }
  51683. }
  51684. };
  51685. /**
  51686. * Use matrix interpolation instead of using direct key value when animating matrices
  51687. */
  51688. Animation.AllowMatricesInterpolation = false;
  51689. /**
  51690. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51691. */
  51692. Animation.AllowMatrixDecomposeForInterpolation = true;
  51693. // Statics
  51694. /**
  51695. * Float animation type
  51696. */
  51697. Animation._ANIMATIONTYPE_FLOAT = 0;
  51698. /**
  51699. * Vector3 animation type
  51700. */
  51701. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51702. /**
  51703. * Quaternion animation type
  51704. */
  51705. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51706. /**
  51707. * Matrix animation type
  51708. */
  51709. Animation._ANIMATIONTYPE_MATRIX = 3;
  51710. /**
  51711. * Color3 animation type
  51712. */
  51713. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51714. /**
  51715. * Vector2 animation type
  51716. */
  51717. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51718. /**
  51719. * Size animation type
  51720. */
  51721. Animation._ANIMATIONTYPE_SIZE = 6;
  51722. /**
  51723. * Relative Loop Mode
  51724. */
  51725. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51726. /**
  51727. * Cycle Loop Mode
  51728. */
  51729. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51730. /**
  51731. * Constant Loop Mode
  51732. */
  51733. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51734. return Animation;
  51735. }());
  51736. BABYLON.Animation = Animation;
  51737. })(BABYLON || (BABYLON = {}));
  51738. //# sourceMappingURL=babylon.animation.js.map
  51739. var BABYLON;
  51740. (function (BABYLON) {
  51741. /**
  51742. * This class defines the direct association between an animation and a target
  51743. */
  51744. var TargetedAnimation = /** @class */ (function () {
  51745. function TargetedAnimation() {
  51746. }
  51747. return TargetedAnimation;
  51748. }());
  51749. BABYLON.TargetedAnimation = TargetedAnimation;
  51750. /**
  51751. * Use this class to create coordinated animations on multiple targets
  51752. */
  51753. var AnimationGroup = /** @class */ (function () {
  51754. function AnimationGroup(name, scene) {
  51755. if (scene === void 0) { scene = null; }
  51756. this.name = name;
  51757. this._targetedAnimations = new Array();
  51758. this._animatables = new Array();
  51759. this._from = Number.MAX_VALUE;
  51760. this._to = -Number.MAX_VALUE;
  51761. this._speedRatio = 1;
  51762. this.onAnimationEndObservable = new BABYLON.Observable();
  51763. /**
  51764. * This observable will notify when all animations have ended.
  51765. */
  51766. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51767. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51768. this._scene.animationGroups.push(this);
  51769. }
  51770. Object.defineProperty(AnimationGroup.prototype, "from", {
  51771. /**
  51772. * Gets the first frame
  51773. */
  51774. get: function () {
  51775. return this._from;
  51776. },
  51777. enumerable: true,
  51778. configurable: true
  51779. });
  51780. Object.defineProperty(AnimationGroup.prototype, "to", {
  51781. /**
  51782. * Gets the last frame
  51783. */
  51784. get: function () {
  51785. return this._to;
  51786. },
  51787. enumerable: true,
  51788. configurable: true
  51789. });
  51790. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51791. /**
  51792. * Define if the animations are started
  51793. */
  51794. get: function () {
  51795. return this._isStarted;
  51796. },
  51797. enumerable: true,
  51798. configurable: true
  51799. });
  51800. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51801. /**
  51802. * Gets or sets the speed ratio to use for all animations
  51803. */
  51804. get: function () {
  51805. return this._speedRatio;
  51806. },
  51807. /**
  51808. * Gets or sets the speed ratio to use for all animations
  51809. */
  51810. set: function (value) {
  51811. if (this._speedRatio === value) {
  51812. return;
  51813. }
  51814. this._speedRatio = value;
  51815. for (var index = 0; index < this._animatables.length; index++) {
  51816. var animatable = this._animatables[index];
  51817. animatable.speedRatio = this._speedRatio;
  51818. }
  51819. },
  51820. enumerable: true,
  51821. configurable: true
  51822. });
  51823. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51824. /**
  51825. * Gets the targeted animations for this animation group
  51826. */
  51827. get: function () {
  51828. return this._targetedAnimations;
  51829. },
  51830. enumerable: true,
  51831. configurable: true
  51832. });
  51833. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51834. /**
  51835. * returning the list of animatables controlled by this animation group.
  51836. */
  51837. get: function () {
  51838. return this._animatables;
  51839. },
  51840. enumerable: true,
  51841. configurable: true
  51842. });
  51843. /**
  51844. * Add an animation (with its target) in the group
  51845. * @param animation defines the animation we want to add
  51846. * @param target defines the target of the animation
  51847. * @returns the {BABYLON.TargetedAnimation} object
  51848. */
  51849. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51850. var targetedAnimation = {
  51851. animation: animation,
  51852. target: target
  51853. };
  51854. var keys = animation.getKeys();
  51855. if (this._from > keys[0].frame) {
  51856. this._from = keys[0].frame;
  51857. }
  51858. if (this._to < keys[keys.length - 1].frame) {
  51859. this._to = keys[keys.length - 1].frame;
  51860. }
  51861. this._targetedAnimations.push(targetedAnimation);
  51862. return targetedAnimation;
  51863. };
  51864. /**
  51865. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51866. * It can add constant keys at begin or end
  51867. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51868. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51869. */
  51870. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51871. if (beginFrame === void 0) { beginFrame = null; }
  51872. if (endFrame === void 0) { endFrame = null; }
  51873. if (beginFrame == null)
  51874. beginFrame = this._from;
  51875. if (endFrame == null)
  51876. endFrame = this._to;
  51877. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51878. var targetedAnimation = this._targetedAnimations[index];
  51879. var keys = targetedAnimation.animation.getKeys();
  51880. var startKey = keys[0];
  51881. var endKey = keys[keys.length - 1];
  51882. if (startKey.frame > beginFrame) {
  51883. var newKey = {
  51884. frame: beginFrame,
  51885. value: startKey.value,
  51886. inTangent: startKey.inTangent,
  51887. outTangent: startKey.outTangent,
  51888. interpolation: startKey.interpolation
  51889. };
  51890. keys.splice(0, 0, newKey);
  51891. }
  51892. if (endKey.frame < endFrame) {
  51893. var newKey = {
  51894. frame: endFrame,
  51895. value: endKey.value,
  51896. inTangent: endKey.outTangent,
  51897. outTangent: endKey.outTangent,
  51898. interpolation: endKey.interpolation
  51899. };
  51900. keys.push(newKey);
  51901. }
  51902. }
  51903. this._from = beginFrame;
  51904. this._to = endFrame;
  51905. return this;
  51906. };
  51907. /**
  51908. * Start all animations on given targets
  51909. * @param loop defines if animations must loop
  51910. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51911. * @param from defines the from key (optional)
  51912. * @param to defines the to key (optional)
  51913. * @returns the current animation group
  51914. */
  51915. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51916. var _this = this;
  51917. if (loop === void 0) { loop = false; }
  51918. if (speedRatio === void 0) { speedRatio = 1; }
  51919. if (this._isStarted || this._targetedAnimations.length === 0) {
  51920. return this;
  51921. }
  51922. var _loop_1 = function (targetedAnimation) {
  51923. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51924. animatable.onAnimationEnd = function () {
  51925. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51926. _this._checkAnimationGroupEnded(animatable);
  51927. };
  51928. this_1._animatables.push(animatable);
  51929. };
  51930. var this_1 = this;
  51931. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51932. var targetedAnimation = _a[_i];
  51933. _loop_1(targetedAnimation);
  51934. }
  51935. this._speedRatio = speedRatio;
  51936. this._isStarted = true;
  51937. return this;
  51938. };
  51939. /**
  51940. * Pause all animations
  51941. */
  51942. AnimationGroup.prototype.pause = function () {
  51943. if (!this._isStarted) {
  51944. return this;
  51945. }
  51946. for (var index = 0; index < this._animatables.length; index++) {
  51947. var animatable = this._animatables[index];
  51948. animatable.pause();
  51949. }
  51950. return this;
  51951. };
  51952. /**
  51953. * Play all animations to initial state
  51954. * This function will start() the animations if they were not started or will restart() them if they were paused
  51955. * @param loop defines if animations must loop
  51956. */
  51957. AnimationGroup.prototype.play = function (loop) {
  51958. // only if all animatables are ready and exist
  51959. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51960. if (loop !== undefined) {
  51961. for (var index = 0; index < this._animatables.length; index++) {
  51962. var animatable = this._animatables[index];
  51963. animatable.loopAnimation = loop;
  51964. }
  51965. }
  51966. this.restart();
  51967. }
  51968. else {
  51969. this.stop();
  51970. this.start(loop, this._speedRatio);
  51971. }
  51972. return this;
  51973. };
  51974. /**
  51975. * Reset all animations to initial state
  51976. */
  51977. AnimationGroup.prototype.reset = function () {
  51978. if (!this._isStarted) {
  51979. return this;
  51980. }
  51981. for (var index = 0; index < this._animatables.length; index++) {
  51982. var animatable = this._animatables[index];
  51983. animatable.reset();
  51984. }
  51985. return this;
  51986. };
  51987. /**
  51988. * Restart animations from key 0
  51989. */
  51990. AnimationGroup.prototype.restart = function () {
  51991. if (!this._isStarted) {
  51992. return this;
  51993. }
  51994. for (var index = 0; index < this._animatables.length; index++) {
  51995. var animatable = this._animatables[index];
  51996. animatable.restart();
  51997. }
  51998. return this;
  51999. };
  52000. /**
  52001. * Stop all animations
  52002. */
  52003. AnimationGroup.prototype.stop = function () {
  52004. if (!this._isStarted) {
  52005. return this;
  52006. }
  52007. for (var index = 0; index < this._animatables.length; index++) {
  52008. var animatable = this._animatables[index];
  52009. animatable.stop();
  52010. }
  52011. this._isStarted = false;
  52012. return this;
  52013. };
  52014. /**
  52015. * Set animation weight for all animatables
  52016. * @param weight defines the weight to use
  52017. * @return the animationGroup
  52018. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52019. */
  52020. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52021. for (var index = 0; index < this._animatables.length; index++) {
  52022. var animatable = this._animatables[index];
  52023. animatable.weight = weight;
  52024. }
  52025. return this;
  52026. };
  52027. /**
  52028. * Synchronize and normalize all animatables with a source animatable
  52029. * @param root defines the root animatable to synchronize with
  52030. * @return the animationGroup
  52031. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52032. */
  52033. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52034. for (var index = 0; index < this._animatables.length; index++) {
  52035. var animatable = this._animatables[index];
  52036. animatable.syncWith(root);
  52037. }
  52038. return this;
  52039. };
  52040. /**
  52041. * Goes to a specific frame in this animation group
  52042. * @param frame the frame number to go to
  52043. * @return the animationGroup
  52044. */
  52045. AnimationGroup.prototype.goToFrame = function (frame) {
  52046. if (!this._isStarted) {
  52047. return this;
  52048. }
  52049. for (var index = 0; index < this._animatables.length; index++) {
  52050. var animatable = this._animatables[index];
  52051. animatable.goToFrame(frame);
  52052. }
  52053. return this;
  52054. };
  52055. /**
  52056. * Dispose all associated resources
  52057. */
  52058. AnimationGroup.prototype.dispose = function () {
  52059. this._targetedAnimations = [];
  52060. this._animatables = [];
  52061. var index = this._scene.animationGroups.indexOf(this);
  52062. if (index > -1) {
  52063. this._scene.animationGroups.splice(index, 1);
  52064. }
  52065. };
  52066. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52067. // animatable should be taken out of the array
  52068. var idx = this._animatables.indexOf(animatable);
  52069. if (idx > -1) {
  52070. this._animatables.splice(idx, 1);
  52071. }
  52072. // all animatables were removed? animation group ended!
  52073. if (this._animatables.length === 0) {
  52074. this._isStarted = false;
  52075. this.onAnimationGroupEndObservable.notifyObservers(this);
  52076. }
  52077. };
  52078. return AnimationGroup;
  52079. }());
  52080. BABYLON.AnimationGroup = AnimationGroup;
  52081. })(BABYLON || (BABYLON = {}));
  52082. //# sourceMappingURL=babylon.animationGroup.js.map
  52083. var BABYLON;
  52084. (function (BABYLON) {
  52085. /**
  52086. * Defines a runtime animation
  52087. */
  52088. var RuntimeAnimation = /** @class */ (function () {
  52089. /**
  52090. * Create a new RuntimeAnimation object
  52091. * @param target defines the target of the animation
  52092. * @param animation defines the source animation object
  52093. * @param scene defines the hosting scene
  52094. * @param host defines the initiating Animatable
  52095. */
  52096. function RuntimeAnimation(target, animation, scene, host) {
  52097. var _this = this;
  52098. this._events = new Array();
  52099. /**
  52100. * The current frame of the runtime animation
  52101. */
  52102. this._currentFrame = 0;
  52103. /**
  52104. * The original value of the runtime animation
  52105. */
  52106. this._originalValue = new Array();
  52107. /**
  52108. * The offsets cache of the runtime animation
  52109. */
  52110. this._offsetsCache = {};
  52111. /**
  52112. * The high limits cache of the runtime animation
  52113. */
  52114. this._highLimitsCache = {};
  52115. /**
  52116. * Specifies if the runtime animation has been stopped
  52117. */
  52118. this._stopped = false;
  52119. /**
  52120. * The blending factor of the runtime animation
  52121. */
  52122. this._blendingFactor = 0;
  52123. /**
  52124. * The target path of the runtime animation
  52125. */
  52126. this._targetPath = "";
  52127. /**
  52128. * The weight of the runtime animation
  52129. */
  52130. this._weight = 1.0;
  52131. /**
  52132. * The ratio offset of the runtime animation
  52133. */
  52134. this._ratioOffset = 0;
  52135. /**
  52136. * The previous delay of the runtime animation
  52137. */
  52138. this._previousDelay = 0;
  52139. /**
  52140. * The previous ratio of the runtime animation
  52141. */
  52142. this._previousRatio = 0;
  52143. this._animation = animation;
  52144. this._target = target;
  52145. this._scene = scene;
  52146. this._host = host;
  52147. animation._runtimeAnimations.push(this);
  52148. // Cloning events locally
  52149. var events = animation.getEvents();
  52150. if (events && events.length > 0) {
  52151. events.forEach(function (e) {
  52152. _this._events.push(e._clone());
  52153. });
  52154. }
  52155. }
  52156. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52157. /**
  52158. * Gets the current frame of the runtime animation
  52159. */
  52160. get: function () {
  52161. return this._currentFrame;
  52162. },
  52163. enumerable: true,
  52164. configurable: true
  52165. });
  52166. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52167. /**
  52168. * Gets the weight of the runtime animation
  52169. */
  52170. get: function () {
  52171. return this._weight;
  52172. },
  52173. enumerable: true,
  52174. configurable: true
  52175. });
  52176. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52177. /**
  52178. * Gets the current value of the runtime animation
  52179. */
  52180. get: function () {
  52181. return this._currentValue;
  52182. },
  52183. enumerable: true,
  52184. configurable: true
  52185. });
  52186. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52187. /**
  52188. * Gets the target path of the runtime animation
  52189. */
  52190. get: function () {
  52191. return this._targetPath;
  52192. },
  52193. enumerable: true,
  52194. configurable: true
  52195. });
  52196. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52197. /**
  52198. * Gets the actual target of the runtime animation
  52199. */
  52200. get: function () {
  52201. return this._activeTarget;
  52202. },
  52203. enumerable: true,
  52204. configurable: true
  52205. });
  52206. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52207. /**
  52208. * Gets the animation from the runtime animation
  52209. */
  52210. get: function () {
  52211. return this._animation;
  52212. },
  52213. enumerable: true,
  52214. configurable: true
  52215. });
  52216. /**
  52217. * Resets the runtime animation to the beginning
  52218. * @param restoreOriginal defines whether to restore the target property to the original value
  52219. */
  52220. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52221. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52222. if (restoreOriginal) {
  52223. if (this._target instanceof Array) {
  52224. var index = 0;
  52225. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52226. var target = _a[_i];
  52227. if (this._originalValue[index] !== undefined) {
  52228. this._setValue(target, this._originalValue[index], -1);
  52229. }
  52230. index++;
  52231. }
  52232. }
  52233. else {
  52234. if (this._originalValue[0] !== undefined) {
  52235. this._setValue(this._target, this._originalValue[0], -1);
  52236. }
  52237. }
  52238. }
  52239. this._offsetsCache = {};
  52240. this._highLimitsCache = {};
  52241. this._currentFrame = 0;
  52242. this._blendingFactor = 0;
  52243. this._originalValue = new Array();
  52244. // Events
  52245. for (var index = 0; index < this._events.length; index++) {
  52246. this._events[index].isDone = false;
  52247. }
  52248. };
  52249. /**
  52250. * Specifies if the runtime animation is stopped
  52251. * @returns Boolean specifying if the runtime animation is stopped
  52252. */
  52253. RuntimeAnimation.prototype.isStopped = function () {
  52254. return this._stopped;
  52255. };
  52256. /**
  52257. * Disposes of the runtime animation
  52258. */
  52259. RuntimeAnimation.prototype.dispose = function () {
  52260. var index = this._animation.runtimeAnimations.indexOf(this);
  52261. if (index > -1) {
  52262. this._animation.runtimeAnimations.splice(index, 1);
  52263. }
  52264. };
  52265. /**
  52266. * Interpolates the animation from the current frame
  52267. * @param currentFrame The frame to interpolate the animation to
  52268. * @param repeatCount The number of times that the animation should loop
  52269. * @param loopMode The type of looping mode to use
  52270. * @param offsetValue Animation offset value
  52271. * @param highLimitValue The high limit value
  52272. * @returns The interpolated value
  52273. */
  52274. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52275. this._currentFrame = currentFrame;
  52276. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52277. this._workValue = BABYLON.Matrix.Zero();
  52278. }
  52279. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52280. };
  52281. /**
  52282. * Apply the interpolated value to the target
  52283. * @param currentValue defines the value computed by the animation
  52284. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52285. */
  52286. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52287. if (weight === void 0) { weight = 1.0; }
  52288. if (this._target instanceof Array) {
  52289. var index = 0;
  52290. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52291. var target = _a[_i];
  52292. this._setValue(target, currentValue, weight, index);
  52293. index++;
  52294. }
  52295. }
  52296. else {
  52297. this._setValue(this._target, currentValue, weight);
  52298. }
  52299. };
  52300. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52301. if (targetIndex === void 0) { targetIndex = 0; }
  52302. // Set value
  52303. var path;
  52304. var destination;
  52305. var targetPropertyPath = this._animation.targetPropertyPath;
  52306. if (targetPropertyPath.length > 1) {
  52307. var property = target[targetPropertyPath[0]];
  52308. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52309. property = property[targetPropertyPath[index]];
  52310. }
  52311. path = targetPropertyPath[targetPropertyPath.length - 1];
  52312. destination = property;
  52313. }
  52314. else {
  52315. path = targetPropertyPath[0];
  52316. destination = target;
  52317. }
  52318. this._targetPath = path;
  52319. this._activeTarget = destination;
  52320. this._weight = weight;
  52321. if (this._originalValue[targetIndex] === undefined) {
  52322. var originalValue = void 0;
  52323. if (destination.getRestPose && path === "_matrix") { // For bones
  52324. originalValue = destination.getRestPose();
  52325. }
  52326. else {
  52327. originalValue = destination[path];
  52328. }
  52329. if (originalValue && originalValue.clone) {
  52330. this._originalValue[targetIndex] = originalValue.clone();
  52331. }
  52332. else {
  52333. this._originalValue[targetIndex] = originalValue;
  52334. }
  52335. }
  52336. // Blending
  52337. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52338. if (enableBlending && this._blendingFactor <= 1.0) {
  52339. if (!this._originalBlendValue) {
  52340. var originalValue = destination[path];
  52341. if (originalValue.clone) {
  52342. this._originalBlendValue = originalValue.clone();
  52343. }
  52344. else {
  52345. this._originalBlendValue = originalValue;
  52346. }
  52347. }
  52348. if (this._originalBlendValue.m) { // Matrix
  52349. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52350. if (this._currentValue) {
  52351. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52352. }
  52353. else {
  52354. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52355. }
  52356. }
  52357. else {
  52358. if (this._currentValue) {
  52359. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52360. }
  52361. else {
  52362. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52363. }
  52364. }
  52365. }
  52366. else {
  52367. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52368. }
  52369. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52370. this._blendingFactor += blendingSpeed;
  52371. }
  52372. else {
  52373. this._currentValue = currentValue;
  52374. }
  52375. if (weight !== -1.0) {
  52376. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52377. }
  52378. else {
  52379. destination[path] = this._currentValue;
  52380. }
  52381. if (target.markAsDirty) {
  52382. target.markAsDirty(this._animation.targetProperty);
  52383. }
  52384. };
  52385. /**
  52386. * Gets the loop pmode of the runtime animation
  52387. * @returns Loop Mode
  52388. */
  52389. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52390. if (this._target && this._target.animationPropertiesOverride) {
  52391. return this._target.animationPropertiesOverride.loopMode;
  52392. }
  52393. return this._animation.loopMode;
  52394. };
  52395. /**
  52396. * Move the current animation to a given frame
  52397. * @param frame defines the frame to move to
  52398. */
  52399. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52400. var keys = this._animation.getKeys();
  52401. if (frame < keys[0].frame) {
  52402. frame = keys[0].frame;
  52403. }
  52404. else if (frame > keys[keys.length - 1].frame) {
  52405. frame = keys[keys.length - 1].frame;
  52406. }
  52407. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52408. this.setValue(currentValue, -1);
  52409. };
  52410. /**
  52411. * @hidden Internal use only
  52412. */
  52413. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52414. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52415. this._ratioOffset = this._previousRatio - newRatio;
  52416. };
  52417. /**
  52418. * Execute the current animation
  52419. * @param delay defines the delay to add to the current frame
  52420. * @param from defines the lower bound of the animation range
  52421. * @param to defines the upper bound of the animation range
  52422. * @param loop defines if the current animation must loop
  52423. * @param speedRatio defines the current speed ratio
  52424. * @param weight defines the weight of the animation (default is -1 so no weight)
  52425. * @returns a boolean indicating if the animation has ended
  52426. */
  52427. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52428. if (weight === void 0) { weight = -1.0; }
  52429. var targetPropertyPath = this._animation.targetPropertyPath;
  52430. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52431. this._stopped = true;
  52432. return false;
  52433. }
  52434. var returnValue = true;
  52435. var keys = this._animation.getKeys();
  52436. // Adding a start key at frame 0 if missing
  52437. if (keys[0].frame !== 0) {
  52438. var newKey = { frame: 0, value: keys[0].value };
  52439. keys.splice(0, 0, newKey);
  52440. }
  52441. // Check limits
  52442. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52443. from = keys[0].frame;
  52444. }
  52445. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52446. to = keys[keys.length - 1].frame;
  52447. }
  52448. //to and from cannot be the same key
  52449. if (from === to) {
  52450. if (from > keys[0].frame) {
  52451. from--;
  52452. }
  52453. else if (to < keys[keys.length - 1].frame) {
  52454. to++;
  52455. }
  52456. }
  52457. // Compute ratio
  52458. var range = to - from;
  52459. var offsetValue;
  52460. // ratio represents the frame delta between from and to
  52461. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52462. var highLimitValue = 0;
  52463. this._previousDelay = delay;
  52464. this._previousRatio = ratio;
  52465. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52466. returnValue = false;
  52467. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52468. }
  52469. else {
  52470. // Get max value if required
  52471. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52472. var keyOffset = to.toString() + from.toString();
  52473. if (!this._offsetsCache[keyOffset]) {
  52474. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52475. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52476. switch (this._animation.dataType) {
  52477. // Float
  52478. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52479. this._offsetsCache[keyOffset] = toValue - fromValue;
  52480. break;
  52481. // Quaternion
  52482. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52483. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52484. break;
  52485. // Vector3
  52486. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52487. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52488. // Vector2
  52489. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52490. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52491. // Size
  52492. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52493. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52494. // Color3
  52495. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52496. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52497. default:
  52498. break;
  52499. }
  52500. this._highLimitsCache[keyOffset] = toValue;
  52501. }
  52502. highLimitValue = this._highLimitsCache[keyOffset];
  52503. offsetValue = this._offsetsCache[keyOffset];
  52504. }
  52505. }
  52506. if (offsetValue === undefined) {
  52507. switch (this._animation.dataType) {
  52508. // Float
  52509. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52510. offsetValue = 0;
  52511. break;
  52512. // Quaternion
  52513. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52514. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52515. break;
  52516. // Vector3
  52517. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52518. offsetValue = BABYLON.Vector3.Zero();
  52519. break;
  52520. // Vector2
  52521. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52522. offsetValue = BABYLON.Vector2.Zero();
  52523. break;
  52524. // Size
  52525. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52526. offsetValue = BABYLON.Size.Zero();
  52527. break;
  52528. // Color3
  52529. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52530. offsetValue = BABYLON.Color3.Black();
  52531. }
  52532. }
  52533. // Compute value
  52534. var repeatCount = (ratio / range) >> 0;
  52535. var currentFrame = returnValue ? from + ratio % range : to;
  52536. // Need to normalize?
  52537. if (this._host && this._host.syncRoot) {
  52538. var syncRoot = this._host.syncRoot;
  52539. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52540. currentFrame = from + (to - from) * hostNormalizedFrame;
  52541. }
  52542. // Reset events if looping
  52543. var events = this._events;
  52544. if (range > 0 && this.currentFrame > currentFrame ||
  52545. range < 0 && this.currentFrame < currentFrame) {
  52546. // Need to reset animation events
  52547. for (var index = 0; index < events.length; index++) {
  52548. if (!events[index].onlyOnce) {
  52549. // reset event, the animation is looping
  52550. events[index].isDone = false;
  52551. }
  52552. }
  52553. }
  52554. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52555. // Set value
  52556. this.setValue(currentValue, weight);
  52557. // Check events
  52558. for (var index = 0; index < events.length; index++) {
  52559. // Make sure current frame has passed event frame and that event frame is within the current range
  52560. // Also, handle both forward and reverse animations
  52561. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52562. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52563. var event = events[index];
  52564. if (!event.isDone) {
  52565. // If event should be done only once, remove it.
  52566. if (event.onlyOnce) {
  52567. events.splice(index, 1);
  52568. index--;
  52569. }
  52570. event.isDone = true;
  52571. event.action();
  52572. } // Don't do anything if the event has already be done.
  52573. }
  52574. }
  52575. if (!returnValue) {
  52576. this._stopped = true;
  52577. }
  52578. return returnValue;
  52579. };
  52580. return RuntimeAnimation;
  52581. }());
  52582. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52583. })(BABYLON || (BABYLON = {}));
  52584. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52585. var BABYLON;
  52586. (function (BABYLON) {
  52587. var Animatable = /** @class */ (function () {
  52588. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52589. if (fromFrame === void 0) { fromFrame = 0; }
  52590. if (toFrame === void 0) { toFrame = 100; }
  52591. if (loopAnimation === void 0) { loopAnimation = false; }
  52592. if (speedRatio === void 0) { speedRatio = 1.0; }
  52593. this.target = target;
  52594. this.fromFrame = fromFrame;
  52595. this.toFrame = toFrame;
  52596. this.loopAnimation = loopAnimation;
  52597. this.onAnimationEnd = onAnimationEnd;
  52598. this._localDelayOffset = null;
  52599. this._pausedDelay = null;
  52600. this._runtimeAnimations = new Array();
  52601. this._paused = false;
  52602. this._speedRatio = 1;
  52603. this._weight = -1.0;
  52604. this.animationStarted = false;
  52605. /**
  52606. * Observer raised when the animation ends
  52607. */
  52608. this.onAnimationEndObservable = new BABYLON.Observable();
  52609. this._scene = scene;
  52610. if (animations) {
  52611. this.appendAnimations(target, animations);
  52612. }
  52613. this._speedRatio = speedRatio;
  52614. scene._activeAnimatables.push(this);
  52615. }
  52616. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52617. /**
  52618. * Gets the root Animatable used to synchronize and normalize animations
  52619. */
  52620. get: function () {
  52621. return this._syncRoot;
  52622. },
  52623. enumerable: true,
  52624. configurable: true
  52625. });
  52626. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52627. /**
  52628. * Gets the current frame of the first RuntimeAnimation
  52629. * Used to synchronize Animatables
  52630. */
  52631. get: function () {
  52632. if (this._runtimeAnimations.length === 0) {
  52633. return 0;
  52634. }
  52635. return this._runtimeAnimations[0].currentFrame;
  52636. },
  52637. enumerable: true,
  52638. configurable: true
  52639. });
  52640. Object.defineProperty(Animatable.prototype, "weight", {
  52641. /**
  52642. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52643. */
  52644. get: function () {
  52645. return this._weight;
  52646. },
  52647. set: function (value) {
  52648. if (value === -1) { // -1 is ok and means no weight
  52649. this._weight = -1;
  52650. return;
  52651. }
  52652. // Else weight must be in [0, 1] range
  52653. this._weight = Math.min(Math.max(value, 0), 1.0);
  52654. },
  52655. enumerable: true,
  52656. configurable: true
  52657. });
  52658. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52659. /**
  52660. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52661. */
  52662. get: function () {
  52663. return this._speedRatio;
  52664. },
  52665. set: function (value) {
  52666. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52667. var animation = this._runtimeAnimations[index];
  52668. animation._prepareForSpeedRatioChange(value);
  52669. }
  52670. this._speedRatio = value;
  52671. },
  52672. enumerable: true,
  52673. configurable: true
  52674. });
  52675. // Methods
  52676. /**
  52677. * Synchronize and normalize current Animatable with a source Animatable
  52678. * This is useful when using animation weights and when animations are not of the same length
  52679. * @param root defines the root Animatable to synchronize with
  52680. * @returns the current Animatable
  52681. */
  52682. Animatable.prototype.syncWith = function (root) {
  52683. this._syncRoot = root;
  52684. if (root) {
  52685. // Make sure this animatable will animate after the root
  52686. var index = this._scene._activeAnimatables.indexOf(this);
  52687. if (index > -1) {
  52688. this._scene._activeAnimatables.splice(index, 1);
  52689. this._scene._activeAnimatables.push(this);
  52690. }
  52691. }
  52692. return this;
  52693. };
  52694. Animatable.prototype.getAnimations = function () {
  52695. return this._runtimeAnimations;
  52696. };
  52697. Animatable.prototype.appendAnimations = function (target, animations) {
  52698. for (var index = 0; index < animations.length; index++) {
  52699. var animation = animations[index];
  52700. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52701. }
  52702. };
  52703. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52704. var runtimeAnimations = this._runtimeAnimations;
  52705. for (var index = 0; index < runtimeAnimations.length; index++) {
  52706. if (runtimeAnimations[index].animation.targetProperty === property) {
  52707. return runtimeAnimations[index].animation;
  52708. }
  52709. }
  52710. return null;
  52711. };
  52712. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52713. var runtimeAnimations = this._runtimeAnimations;
  52714. for (var index = 0; index < runtimeAnimations.length; index++) {
  52715. if (runtimeAnimations[index].animation.targetProperty === property) {
  52716. return runtimeAnimations[index];
  52717. }
  52718. }
  52719. return null;
  52720. };
  52721. Animatable.prototype.reset = function () {
  52722. var runtimeAnimations = this._runtimeAnimations;
  52723. for (var index = 0; index < runtimeAnimations.length; index++) {
  52724. runtimeAnimations[index].reset(true);
  52725. }
  52726. this._localDelayOffset = null;
  52727. this._pausedDelay = null;
  52728. };
  52729. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52730. var runtimeAnimations = this._runtimeAnimations;
  52731. for (var index = 0; index < runtimeAnimations.length; index++) {
  52732. runtimeAnimations[index].animation.enableBlending = true;
  52733. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52734. }
  52735. };
  52736. Animatable.prototype.disableBlending = function () {
  52737. var runtimeAnimations = this._runtimeAnimations;
  52738. for (var index = 0; index < runtimeAnimations.length; index++) {
  52739. runtimeAnimations[index].animation.enableBlending = false;
  52740. }
  52741. };
  52742. Animatable.prototype.goToFrame = function (frame) {
  52743. var runtimeAnimations = this._runtimeAnimations;
  52744. if (runtimeAnimations[0]) {
  52745. var fps = runtimeAnimations[0].animation.framePerSecond;
  52746. var currentFrame = runtimeAnimations[0].currentFrame;
  52747. var adjustTime = frame - currentFrame;
  52748. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52749. if (this._localDelayOffset === null) {
  52750. this._localDelayOffset = 0;
  52751. }
  52752. this._localDelayOffset -= delay;
  52753. }
  52754. for (var index = 0; index < runtimeAnimations.length; index++) {
  52755. runtimeAnimations[index].goToFrame(frame);
  52756. }
  52757. };
  52758. Animatable.prototype.pause = function () {
  52759. if (this._paused) {
  52760. return;
  52761. }
  52762. this._paused = true;
  52763. };
  52764. Animatable.prototype.restart = function () {
  52765. this._paused = false;
  52766. };
  52767. Animatable.prototype._raiseOnAnimationEnd = function () {
  52768. if (this.onAnimationEnd) {
  52769. this.onAnimationEnd();
  52770. }
  52771. this.onAnimationEndObservable.notifyObservers(this);
  52772. };
  52773. Animatable.prototype.stop = function (animationName) {
  52774. if (animationName) {
  52775. var idx = this._scene._activeAnimatables.indexOf(this);
  52776. if (idx > -1) {
  52777. var runtimeAnimations = this._runtimeAnimations;
  52778. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52779. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52780. continue;
  52781. }
  52782. runtimeAnimations[index].dispose();
  52783. runtimeAnimations.splice(index, 1);
  52784. }
  52785. if (runtimeAnimations.length == 0) {
  52786. this._scene._activeAnimatables.splice(idx, 1);
  52787. this._raiseOnAnimationEnd();
  52788. }
  52789. }
  52790. }
  52791. else {
  52792. var index = this._scene._activeAnimatables.indexOf(this);
  52793. if (index > -1) {
  52794. this._scene._activeAnimatables.splice(index, 1);
  52795. var runtimeAnimations = this._runtimeAnimations;
  52796. for (var index = 0; index < runtimeAnimations.length; index++) {
  52797. runtimeAnimations[index].dispose();
  52798. }
  52799. this._raiseOnAnimationEnd();
  52800. }
  52801. }
  52802. };
  52803. /**
  52804. * Wait asynchronously for the animation to end
  52805. * @returns a promise which will be fullfilled when the animation ends
  52806. */
  52807. Animatable.prototype.waitAsync = function () {
  52808. var _this = this;
  52809. return new Promise(function (resolve, reject) {
  52810. _this.onAnimationEndObservable.add(function () {
  52811. resolve(_this);
  52812. }, undefined, undefined, _this, true);
  52813. });
  52814. };
  52815. /** @hidden */
  52816. Animatable.prototype._animate = function (delay) {
  52817. if (this._paused) {
  52818. this.animationStarted = false;
  52819. if (this._pausedDelay === null) {
  52820. this._pausedDelay = delay;
  52821. }
  52822. return true;
  52823. }
  52824. if (this._localDelayOffset === null) {
  52825. this._localDelayOffset = delay;
  52826. this._pausedDelay = null;
  52827. }
  52828. else if (this._pausedDelay !== null) {
  52829. this._localDelayOffset += delay - this._pausedDelay;
  52830. this._pausedDelay = null;
  52831. }
  52832. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52833. return true;
  52834. }
  52835. // Animating
  52836. var running = false;
  52837. var runtimeAnimations = this._runtimeAnimations;
  52838. var index;
  52839. for (index = 0; index < runtimeAnimations.length; index++) {
  52840. var animation = runtimeAnimations[index];
  52841. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52842. running = running || isRunning;
  52843. }
  52844. this.animationStarted = running;
  52845. if (!running) {
  52846. // Remove from active animatables
  52847. index = this._scene._activeAnimatables.indexOf(this);
  52848. this._scene._activeAnimatables.splice(index, 1);
  52849. // Dispose all runtime animations
  52850. for (index = 0; index < runtimeAnimations.length; index++) {
  52851. runtimeAnimations[index].dispose();
  52852. }
  52853. this._raiseOnAnimationEnd();
  52854. this.onAnimationEnd = null;
  52855. this.onAnimationEndObservable.clear();
  52856. }
  52857. return running;
  52858. };
  52859. return Animatable;
  52860. }());
  52861. BABYLON.Animatable = Animatable;
  52862. })(BABYLON || (BABYLON = {}));
  52863. //# sourceMappingURL=babylon.animatable.js.map
  52864. var BABYLON;
  52865. (function (BABYLON) {
  52866. var EasingFunction = /** @class */ (function () {
  52867. function EasingFunction() {
  52868. // Properties
  52869. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52870. }
  52871. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52872. get: function () {
  52873. return EasingFunction._EASINGMODE_EASEIN;
  52874. },
  52875. enumerable: true,
  52876. configurable: true
  52877. });
  52878. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52879. get: function () {
  52880. return EasingFunction._EASINGMODE_EASEOUT;
  52881. },
  52882. enumerable: true,
  52883. configurable: true
  52884. });
  52885. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52886. get: function () {
  52887. return EasingFunction._EASINGMODE_EASEINOUT;
  52888. },
  52889. enumerable: true,
  52890. configurable: true
  52891. });
  52892. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52893. var n = Math.min(Math.max(easingMode, 0), 2);
  52894. this._easingMode = n;
  52895. };
  52896. EasingFunction.prototype.getEasingMode = function () {
  52897. return this._easingMode;
  52898. };
  52899. EasingFunction.prototype.easeInCore = function (gradient) {
  52900. throw new Error('You must implement this method');
  52901. };
  52902. EasingFunction.prototype.ease = function (gradient) {
  52903. switch (this._easingMode) {
  52904. case EasingFunction.EASINGMODE_EASEIN:
  52905. return this.easeInCore(gradient);
  52906. case EasingFunction.EASINGMODE_EASEOUT:
  52907. return (1 - this.easeInCore(1 - gradient));
  52908. }
  52909. if (gradient >= 0.5) {
  52910. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52911. }
  52912. return (this.easeInCore(gradient * 2) * 0.5);
  52913. };
  52914. //Statics
  52915. EasingFunction._EASINGMODE_EASEIN = 0;
  52916. EasingFunction._EASINGMODE_EASEOUT = 1;
  52917. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52918. return EasingFunction;
  52919. }());
  52920. BABYLON.EasingFunction = EasingFunction;
  52921. var CircleEase = /** @class */ (function (_super) {
  52922. __extends(CircleEase, _super);
  52923. function CircleEase() {
  52924. return _super !== null && _super.apply(this, arguments) || this;
  52925. }
  52926. CircleEase.prototype.easeInCore = function (gradient) {
  52927. gradient = Math.max(0, Math.min(1, gradient));
  52928. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52929. };
  52930. return CircleEase;
  52931. }(EasingFunction));
  52932. BABYLON.CircleEase = CircleEase;
  52933. var BackEase = /** @class */ (function (_super) {
  52934. __extends(BackEase, _super);
  52935. function BackEase(amplitude) {
  52936. if (amplitude === void 0) { amplitude = 1; }
  52937. var _this = _super.call(this) || this;
  52938. _this.amplitude = amplitude;
  52939. return _this;
  52940. }
  52941. BackEase.prototype.easeInCore = function (gradient) {
  52942. var num = Math.max(0, this.amplitude);
  52943. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52944. };
  52945. return BackEase;
  52946. }(EasingFunction));
  52947. BABYLON.BackEase = BackEase;
  52948. var BounceEase = /** @class */ (function (_super) {
  52949. __extends(BounceEase, _super);
  52950. function BounceEase(bounces, bounciness) {
  52951. if (bounces === void 0) { bounces = 3; }
  52952. if (bounciness === void 0) { bounciness = 2; }
  52953. var _this = _super.call(this) || this;
  52954. _this.bounces = bounces;
  52955. _this.bounciness = bounciness;
  52956. return _this;
  52957. }
  52958. BounceEase.prototype.easeInCore = function (gradient) {
  52959. var y = Math.max(0.0, this.bounces);
  52960. var bounciness = this.bounciness;
  52961. if (bounciness <= 1.0) {
  52962. bounciness = 1.001;
  52963. }
  52964. var num9 = Math.pow(bounciness, y);
  52965. var num5 = 1.0 - bounciness;
  52966. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52967. var num15 = gradient * num4;
  52968. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52969. var num3 = Math.floor(num65);
  52970. var num13 = num3 + 1.0;
  52971. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52972. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52973. var num7 = (num8 + num12) * 0.5;
  52974. var num6 = gradient - num7;
  52975. var num2 = num7 - num8;
  52976. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52977. };
  52978. return BounceEase;
  52979. }(EasingFunction));
  52980. BABYLON.BounceEase = BounceEase;
  52981. var CubicEase = /** @class */ (function (_super) {
  52982. __extends(CubicEase, _super);
  52983. function CubicEase() {
  52984. return _super !== null && _super.apply(this, arguments) || this;
  52985. }
  52986. CubicEase.prototype.easeInCore = function (gradient) {
  52987. return (gradient * gradient * gradient);
  52988. };
  52989. return CubicEase;
  52990. }(EasingFunction));
  52991. BABYLON.CubicEase = CubicEase;
  52992. var ElasticEase = /** @class */ (function (_super) {
  52993. __extends(ElasticEase, _super);
  52994. function ElasticEase(oscillations, springiness) {
  52995. if (oscillations === void 0) { oscillations = 3; }
  52996. if (springiness === void 0) { springiness = 3; }
  52997. var _this = _super.call(this) || this;
  52998. _this.oscillations = oscillations;
  52999. _this.springiness = springiness;
  53000. return _this;
  53001. }
  53002. ElasticEase.prototype.easeInCore = function (gradient) {
  53003. var num2;
  53004. var num3 = Math.max(0.0, this.oscillations);
  53005. var num = Math.max(0.0, this.springiness);
  53006. if (num == 0) {
  53007. num2 = gradient;
  53008. }
  53009. else {
  53010. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53011. }
  53012. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53013. };
  53014. return ElasticEase;
  53015. }(EasingFunction));
  53016. BABYLON.ElasticEase = ElasticEase;
  53017. var ExponentialEase = /** @class */ (function (_super) {
  53018. __extends(ExponentialEase, _super);
  53019. function ExponentialEase(exponent) {
  53020. if (exponent === void 0) { exponent = 2; }
  53021. var _this = _super.call(this) || this;
  53022. _this.exponent = exponent;
  53023. return _this;
  53024. }
  53025. ExponentialEase.prototype.easeInCore = function (gradient) {
  53026. if (this.exponent <= 0) {
  53027. return gradient;
  53028. }
  53029. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53030. };
  53031. return ExponentialEase;
  53032. }(EasingFunction));
  53033. BABYLON.ExponentialEase = ExponentialEase;
  53034. var PowerEase = /** @class */ (function (_super) {
  53035. __extends(PowerEase, _super);
  53036. function PowerEase(power) {
  53037. if (power === void 0) { power = 2; }
  53038. var _this = _super.call(this) || this;
  53039. _this.power = power;
  53040. return _this;
  53041. }
  53042. PowerEase.prototype.easeInCore = function (gradient) {
  53043. var y = Math.max(0.0, this.power);
  53044. return Math.pow(gradient, y);
  53045. };
  53046. return PowerEase;
  53047. }(EasingFunction));
  53048. BABYLON.PowerEase = PowerEase;
  53049. var QuadraticEase = /** @class */ (function (_super) {
  53050. __extends(QuadraticEase, _super);
  53051. function QuadraticEase() {
  53052. return _super !== null && _super.apply(this, arguments) || this;
  53053. }
  53054. QuadraticEase.prototype.easeInCore = function (gradient) {
  53055. return (gradient * gradient);
  53056. };
  53057. return QuadraticEase;
  53058. }(EasingFunction));
  53059. BABYLON.QuadraticEase = QuadraticEase;
  53060. var QuarticEase = /** @class */ (function (_super) {
  53061. __extends(QuarticEase, _super);
  53062. function QuarticEase() {
  53063. return _super !== null && _super.apply(this, arguments) || this;
  53064. }
  53065. QuarticEase.prototype.easeInCore = function (gradient) {
  53066. return (gradient * gradient * gradient * gradient);
  53067. };
  53068. return QuarticEase;
  53069. }(EasingFunction));
  53070. BABYLON.QuarticEase = QuarticEase;
  53071. var QuinticEase = /** @class */ (function (_super) {
  53072. __extends(QuinticEase, _super);
  53073. function QuinticEase() {
  53074. return _super !== null && _super.apply(this, arguments) || this;
  53075. }
  53076. QuinticEase.prototype.easeInCore = function (gradient) {
  53077. return (gradient * gradient * gradient * gradient * gradient);
  53078. };
  53079. return QuinticEase;
  53080. }(EasingFunction));
  53081. BABYLON.QuinticEase = QuinticEase;
  53082. var SineEase = /** @class */ (function (_super) {
  53083. __extends(SineEase, _super);
  53084. function SineEase() {
  53085. return _super !== null && _super.apply(this, arguments) || this;
  53086. }
  53087. SineEase.prototype.easeInCore = function (gradient) {
  53088. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53089. };
  53090. return SineEase;
  53091. }(EasingFunction));
  53092. BABYLON.SineEase = SineEase;
  53093. var BezierCurveEase = /** @class */ (function (_super) {
  53094. __extends(BezierCurveEase, _super);
  53095. function BezierCurveEase(x1, y1, x2, y2) {
  53096. if (x1 === void 0) { x1 = 0; }
  53097. if (y1 === void 0) { y1 = 0; }
  53098. if (x2 === void 0) { x2 = 1; }
  53099. if (y2 === void 0) { y2 = 1; }
  53100. var _this = _super.call(this) || this;
  53101. _this.x1 = x1;
  53102. _this.y1 = y1;
  53103. _this.x2 = x2;
  53104. _this.y2 = y2;
  53105. return _this;
  53106. }
  53107. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53108. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53109. };
  53110. return BezierCurveEase;
  53111. }(EasingFunction));
  53112. BABYLON.BezierCurveEase = BezierCurveEase;
  53113. })(BABYLON || (BABYLON = {}));
  53114. //# sourceMappingURL=babylon.easing.js.map
  53115. var BABYLON;
  53116. (function (BABYLON) {
  53117. /**
  53118. * A Condition applied to an Action
  53119. */
  53120. var Condition = /** @class */ (function () {
  53121. /**
  53122. * Creates a new Condition
  53123. * @param actionManager the manager of the action the condition is applied to
  53124. */
  53125. function Condition(actionManager) {
  53126. this._actionManager = actionManager;
  53127. }
  53128. /**
  53129. * Check if the current condition is valid
  53130. * @returns a boolean
  53131. */
  53132. Condition.prototype.isValid = function () {
  53133. return true;
  53134. };
  53135. /**
  53136. * Internal only
  53137. * @hidden
  53138. */
  53139. Condition.prototype._getProperty = function (propertyPath) {
  53140. return this._actionManager._getProperty(propertyPath);
  53141. };
  53142. /**
  53143. * Internal only
  53144. * @hidden
  53145. */
  53146. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53147. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53148. };
  53149. /**
  53150. * Serialize placeholder for child classes
  53151. * @returns the serialized object
  53152. */
  53153. Condition.prototype.serialize = function () {
  53154. };
  53155. /**
  53156. * Internal only
  53157. * @hidden
  53158. */
  53159. Condition.prototype._serialize = function (serializedCondition) {
  53160. return {
  53161. type: 2,
  53162. children: [],
  53163. name: serializedCondition.name,
  53164. properties: serializedCondition.properties
  53165. };
  53166. };
  53167. return Condition;
  53168. }());
  53169. BABYLON.Condition = Condition;
  53170. /**
  53171. * Defines specific conditional operators as extensions of Condition
  53172. */
  53173. var ValueCondition = /** @class */ (function (_super) {
  53174. __extends(ValueCondition, _super);
  53175. /**
  53176. * Creates a new ValueCondition
  53177. * @param actionManager manager for the action the condition applies to
  53178. * @param target for the action
  53179. * @param propertyPath path to specify the property of the target the conditional operator uses
  53180. * @param value the value compared by the conditional operator against the current value of the property
  53181. * @param operator the conditional operator, default ValueCondition.IsEqual
  53182. */
  53183. function ValueCondition(actionManager, target,
  53184. /** path to specify the property of the target the conditional operator uses */
  53185. propertyPath,
  53186. /** the value compared by the conditional operator against the current value of the property */
  53187. value,
  53188. /** the conditional operator, default ValueCondition.IsEqual */
  53189. operator) {
  53190. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53191. var _this = _super.call(this, actionManager) || this;
  53192. _this.propertyPath = propertyPath;
  53193. _this.value = value;
  53194. _this.operator = operator;
  53195. _this._target = target;
  53196. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53197. _this._property = _this._getProperty(_this.propertyPath);
  53198. return _this;
  53199. }
  53200. Object.defineProperty(ValueCondition, "IsEqual", {
  53201. /**
  53202. * returns the number for IsEqual
  53203. */
  53204. get: function () {
  53205. return ValueCondition._IsEqual;
  53206. },
  53207. enumerable: true,
  53208. configurable: true
  53209. });
  53210. Object.defineProperty(ValueCondition, "IsDifferent", {
  53211. /**
  53212. * Returns the number for IsDifferent
  53213. */
  53214. get: function () {
  53215. return ValueCondition._IsDifferent;
  53216. },
  53217. enumerable: true,
  53218. configurable: true
  53219. });
  53220. Object.defineProperty(ValueCondition, "IsGreater", {
  53221. /**
  53222. * Returns the number for IsGreater
  53223. */
  53224. get: function () {
  53225. return ValueCondition._IsGreater;
  53226. },
  53227. enumerable: true,
  53228. configurable: true
  53229. });
  53230. Object.defineProperty(ValueCondition, "IsLesser", {
  53231. /**
  53232. * Returns the number for IsLesser
  53233. */
  53234. get: function () {
  53235. return ValueCondition._IsLesser;
  53236. },
  53237. enumerable: true,
  53238. configurable: true
  53239. });
  53240. /**
  53241. * Compares the given value with the property value for the specified conditional operator
  53242. * @returns the result of the comparison
  53243. */
  53244. ValueCondition.prototype.isValid = function () {
  53245. switch (this.operator) {
  53246. case ValueCondition.IsGreater:
  53247. return this._effectiveTarget[this._property] > this.value;
  53248. case ValueCondition.IsLesser:
  53249. return this._effectiveTarget[this._property] < this.value;
  53250. case ValueCondition.IsEqual:
  53251. case ValueCondition.IsDifferent:
  53252. var check;
  53253. if (this.value.equals) {
  53254. check = this.value.equals(this._effectiveTarget[this._property]);
  53255. }
  53256. else {
  53257. check = this.value === this._effectiveTarget[this._property];
  53258. }
  53259. return this.operator === ValueCondition.IsEqual ? check : !check;
  53260. }
  53261. return false;
  53262. };
  53263. /**
  53264. * Serialize the ValueCondition into a JSON compatible object
  53265. * @returns serialization object
  53266. */
  53267. ValueCondition.prototype.serialize = function () {
  53268. return this._serialize({
  53269. name: "ValueCondition",
  53270. properties: [
  53271. BABYLON.Action._GetTargetProperty(this._target),
  53272. { name: "propertyPath", value: this.propertyPath },
  53273. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53274. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53275. ]
  53276. });
  53277. };
  53278. /**
  53279. * Gets the name of the conditional operator for the ValueCondition
  53280. * @param operator the conditional operator
  53281. * @returns the name
  53282. */
  53283. ValueCondition.GetOperatorName = function (operator) {
  53284. switch (operator) {
  53285. case ValueCondition._IsEqual: return "IsEqual";
  53286. case ValueCondition._IsDifferent: return "IsDifferent";
  53287. case ValueCondition._IsGreater: return "IsGreater";
  53288. case ValueCondition._IsLesser: return "IsLesser";
  53289. default: return "";
  53290. }
  53291. };
  53292. /**
  53293. * Internal only
  53294. * @hidden
  53295. */
  53296. ValueCondition._IsEqual = 0;
  53297. /**
  53298. * Internal only
  53299. * @hidden
  53300. */
  53301. ValueCondition._IsDifferent = 1;
  53302. /**
  53303. * Internal only
  53304. * @hidden
  53305. */
  53306. ValueCondition._IsGreater = 2;
  53307. /**
  53308. * Internal only
  53309. * @hidden
  53310. */
  53311. ValueCondition._IsLesser = 3;
  53312. return ValueCondition;
  53313. }(Condition));
  53314. BABYLON.ValueCondition = ValueCondition;
  53315. /**
  53316. * Defines a predicate condition as an extension of Condition
  53317. */
  53318. var PredicateCondition = /** @class */ (function (_super) {
  53319. __extends(PredicateCondition, _super);
  53320. /**
  53321. * Creates a new PredicateCondition
  53322. * @param actionManager manager for the action the condition applies to
  53323. * @param predicate defines the predicate function used to validate the condition
  53324. */
  53325. function PredicateCondition(actionManager,
  53326. /** defines the predicate function used to validate the condition */
  53327. predicate) {
  53328. var _this = _super.call(this, actionManager) || this;
  53329. _this.predicate = predicate;
  53330. return _this;
  53331. }
  53332. /**
  53333. * @returns the validity of the predicate condition
  53334. */
  53335. PredicateCondition.prototype.isValid = function () {
  53336. return this.predicate();
  53337. };
  53338. return PredicateCondition;
  53339. }(Condition));
  53340. BABYLON.PredicateCondition = PredicateCondition;
  53341. /**
  53342. * Defines a state condition as an extension of Condition
  53343. */
  53344. var StateCondition = /** @class */ (function (_super) {
  53345. __extends(StateCondition, _super);
  53346. /**
  53347. * Creates a new StateCondition
  53348. * @param actionManager manager for the action the condition applies to
  53349. * @param target of the condition
  53350. * @param value to compare with target state
  53351. */
  53352. function StateCondition(actionManager, target, value) {
  53353. var _this = _super.call(this, actionManager) || this;
  53354. _this.value = value;
  53355. _this._target = target;
  53356. return _this;
  53357. }
  53358. /**
  53359. * @returns the validity of the state
  53360. */
  53361. StateCondition.prototype.isValid = function () {
  53362. return this._target.state === this.value;
  53363. };
  53364. /**
  53365. * Serialize the StateCondition into a JSON compatible object
  53366. * @returns serialization object
  53367. */
  53368. StateCondition.prototype.serialize = function () {
  53369. return this._serialize({
  53370. name: "StateCondition",
  53371. properties: [
  53372. BABYLON.Action._GetTargetProperty(this._target),
  53373. { name: "value", value: this.value }
  53374. ]
  53375. });
  53376. };
  53377. return StateCondition;
  53378. }(Condition));
  53379. BABYLON.StateCondition = StateCondition;
  53380. })(BABYLON || (BABYLON = {}));
  53381. //# sourceMappingURL=babylon.condition.js.map
  53382. var BABYLON;
  53383. (function (BABYLON) {
  53384. /**
  53385. * The action to be carried out following a trigger
  53386. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53387. */
  53388. var Action = /** @class */ (function () {
  53389. /**
  53390. * Creates a new Action
  53391. * @param triggerOptions the trigger, with or without parameters, for the action
  53392. * @param condition an optional determinant of action
  53393. */
  53394. function Action(
  53395. /** the trigger, with or without parameters, for the action */
  53396. triggerOptions, condition) {
  53397. this.triggerOptions = triggerOptions;
  53398. /**
  53399. * An event triggered prior to action being executed.
  53400. */
  53401. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53402. if (triggerOptions.parameter) {
  53403. this.trigger = triggerOptions.trigger;
  53404. this._triggerParameter = triggerOptions.parameter;
  53405. }
  53406. else {
  53407. this.trigger = triggerOptions;
  53408. }
  53409. this._nextActiveAction = this;
  53410. this._condition = condition;
  53411. }
  53412. /**
  53413. * Internal only
  53414. * @hidden
  53415. */
  53416. Action.prototype._prepare = function () {
  53417. };
  53418. /**
  53419. * Gets the trigger parameters
  53420. * @returns the trigger parameters
  53421. */
  53422. Action.prototype.getTriggerParameter = function () {
  53423. return this._triggerParameter;
  53424. };
  53425. /**
  53426. * Internal only - executes current action event
  53427. * @hidden
  53428. */
  53429. Action.prototype._executeCurrent = function (evt) {
  53430. if (this._nextActiveAction._condition) {
  53431. var condition = this._nextActiveAction._condition;
  53432. var currentRenderId = this._actionManager.getScene().getRenderId();
  53433. // We cache the current evaluation for the current frame
  53434. if (condition._evaluationId === currentRenderId) {
  53435. if (!condition._currentResult) {
  53436. return;
  53437. }
  53438. }
  53439. else {
  53440. condition._evaluationId = currentRenderId;
  53441. if (!condition.isValid()) {
  53442. condition._currentResult = false;
  53443. return;
  53444. }
  53445. condition._currentResult = true;
  53446. }
  53447. }
  53448. this.onBeforeExecuteObservable.notifyObservers(this);
  53449. this._nextActiveAction.execute(evt);
  53450. this.skipToNextActiveAction();
  53451. };
  53452. /**
  53453. * Execute placeholder for child classes
  53454. * @param evt optional action event
  53455. */
  53456. Action.prototype.execute = function (evt) {
  53457. };
  53458. /**
  53459. * Skips to next active action
  53460. */
  53461. Action.prototype.skipToNextActiveAction = function () {
  53462. if (this._nextActiveAction._child) {
  53463. if (!this._nextActiveAction._child._actionManager) {
  53464. this._nextActiveAction._child._actionManager = this._actionManager;
  53465. }
  53466. this._nextActiveAction = this._nextActiveAction._child;
  53467. }
  53468. else {
  53469. this._nextActiveAction = this;
  53470. }
  53471. };
  53472. /**
  53473. * Adds action to chain of actions, may be a DoNothingAction
  53474. * @param action defines the next action to execute
  53475. * @returns The action passed in
  53476. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53477. */
  53478. Action.prototype.then = function (action) {
  53479. this._child = action;
  53480. action._actionManager = this._actionManager;
  53481. action._prepare();
  53482. return action;
  53483. };
  53484. /**
  53485. * Internal only
  53486. * @hidden
  53487. */
  53488. Action.prototype._getProperty = function (propertyPath) {
  53489. return this._actionManager._getProperty(propertyPath);
  53490. };
  53491. /**
  53492. * Internal only
  53493. * @hidden
  53494. */
  53495. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53496. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53497. };
  53498. /**
  53499. * Serialize placeholder for child classes
  53500. * @param parent of child
  53501. * @returns the serialized object
  53502. */
  53503. Action.prototype.serialize = function (parent) {
  53504. };
  53505. /**
  53506. * Internal only called by serialize
  53507. * @hidden
  53508. */
  53509. Action.prototype._serialize = function (serializedAction, parent) {
  53510. var serializationObject = {
  53511. type: 1,
  53512. children: [],
  53513. name: serializedAction.name,
  53514. properties: serializedAction.properties || []
  53515. };
  53516. // Serialize child
  53517. if (this._child) {
  53518. this._child.serialize(serializationObject);
  53519. }
  53520. // Check if "this" has a condition
  53521. if (this._condition) {
  53522. var serializedCondition = this._condition.serialize();
  53523. serializedCondition.children.push(serializationObject);
  53524. if (parent) {
  53525. parent.children.push(serializedCondition);
  53526. }
  53527. return serializedCondition;
  53528. }
  53529. if (parent) {
  53530. parent.children.push(serializationObject);
  53531. }
  53532. return serializationObject;
  53533. };
  53534. /**
  53535. * Internal only
  53536. * @hidden
  53537. */
  53538. Action._SerializeValueAsString = function (value) {
  53539. if (typeof value === "number") {
  53540. return value.toString();
  53541. }
  53542. if (typeof value === "boolean") {
  53543. return value ? "true" : "false";
  53544. }
  53545. if (value instanceof BABYLON.Vector2) {
  53546. return value.x + ", " + value.y;
  53547. }
  53548. if (value instanceof BABYLON.Vector3) {
  53549. return value.x + ", " + value.y + ", " + value.z;
  53550. }
  53551. if (value instanceof BABYLON.Color3) {
  53552. return value.r + ", " + value.g + ", " + value.b;
  53553. }
  53554. if (value instanceof BABYLON.Color4) {
  53555. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53556. }
  53557. return value; // string
  53558. };
  53559. /**
  53560. * Internal only
  53561. * @hidden
  53562. */
  53563. Action._GetTargetProperty = function (target) {
  53564. return {
  53565. name: "target",
  53566. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53567. : target instanceof BABYLON.Light ? "LightProperties"
  53568. : target instanceof BABYLON.Camera ? "CameraProperties"
  53569. : "SceneProperties",
  53570. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53571. };
  53572. };
  53573. return Action;
  53574. }());
  53575. BABYLON.Action = Action;
  53576. })(BABYLON || (BABYLON = {}));
  53577. //# sourceMappingURL=babylon.action.js.map
  53578. var BABYLON;
  53579. (function (BABYLON) {
  53580. /**
  53581. * ActionEvent is the event being sent when an action is triggered.
  53582. */
  53583. var ActionEvent = /** @class */ (function () {
  53584. /**
  53585. * Creates a new ActionEvent
  53586. * @param source The mesh or sprite that triggered the action
  53587. * @param pointerX The X mouse cursor position at the time of the event
  53588. * @param pointerY The Y mouse cursor position at the time of the event
  53589. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53590. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53591. * @param additionalData additional data for the event
  53592. */
  53593. function ActionEvent(
  53594. /** The mesh or sprite that triggered the action */
  53595. source,
  53596. /** The X mouse cursor position at the time of the event */
  53597. pointerX,
  53598. /** The Y mouse cursor position at the time of the event */
  53599. pointerY,
  53600. /** The mesh that is currently pointed at (can be null) */
  53601. meshUnderPointer,
  53602. /** the original (browser) event that triggered the ActionEvent */
  53603. sourceEvent,
  53604. /** additional data for the event */
  53605. additionalData) {
  53606. this.source = source;
  53607. this.pointerX = pointerX;
  53608. this.pointerY = pointerY;
  53609. this.meshUnderPointer = meshUnderPointer;
  53610. this.sourceEvent = sourceEvent;
  53611. this.additionalData = additionalData;
  53612. }
  53613. /**
  53614. * Helper function to auto-create an ActionEvent from a source mesh.
  53615. * @param source The source mesh that triggered the event
  53616. * @param evt The original (browser) event
  53617. * @param additionalData additional data for the event
  53618. * @returns the new ActionEvent
  53619. */
  53620. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53621. var scene = source.getScene();
  53622. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53623. };
  53624. /**
  53625. * Helper function to auto-create an ActionEvent from a source sprite
  53626. * @param source The source sprite that triggered the event
  53627. * @param scene Scene associated with the sprite
  53628. * @param evt The original (browser) event
  53629. * @param additionalData additional data for the event
  53630. * @returns the new ActionEvent
  53631. */
  53632. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53633. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53634. };
  53635. /**
  53636. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53637. * @param scene the scene where the event occurred
  53638. * @param evt The original (browser) event
  53639. * @returns the new ActionEvent
  53640. */
  53641. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53642. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53643. };
  53644. /**
  53645. * Helper function to auto-create an ActionEvent from a primitive
  53646. * @param prim defines the target primitive
  53647. * @param pointerPos defines the pointer position
  53648. * @param evt The original (browser) event
  53649. * @param additionalData additional data for the event
  53650. * @returns the new ActionEvent
  53651. */
  53652. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53653. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53654. };
  53655. return ActionEvent;
  53656. }());
  53657. BABYLON.ActionEvent = ActionEvent;
  53658. /**
  53659. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53660. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53661. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53662. */
  53663. var ActionManager = /** @class */ (function () {
  53664. /**
  53665. * Creates a new action manager
  53666. * @param scene defines the hosting scene
  53667. */
  53668. function ActionManager(scene) {
  53669. // Members
  53670. /** Gets the list of actions */
  53671. this.actions = new Array();
  53672. /** Gets the cursor to use when hovering items */
  53673. this.hoverCursor = '';
  53674. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53675. scene._actionManagers.push(this);
  53676. }
  53677. Object.defineProperty(ActionManager, "NothingTrigger", {
  53678. /**
  53679. * Nothing
  53680. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53681. */
  53682. get: function () {
  53683. return ActionManager._NothingTrigger;
  53684. },
  53685. enumerable: true,
  53686. configurable: true
  53687. });
  53688. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53689. /**
  53690. * On pick
  53691. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53692. */
  53693. get: function () {
  53694. return ActionManager._OnPickTrigger;
  53695. },
  53696. enumerable: true,
  53697. configurable: true
  53698. });
  53699. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53700. /**
  53701. * On left pick
  53702. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53703. */
  53704. get: function () {
  53705. return ActionManager._OnLeftPickTrigger;
  53706. },
  53707. enumerable: true,
  53708. configurable: true
  53709. });
  53710. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53711. /**
  53712. * On right pick
  53713. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53714. */
  53715. get: function () {
  53716. return ActionManager._OnRightPickTrigger;
  53717. },
  53718. enumerable: true,
  53719. configurable: true
  53720. });
  53721. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53722. /**
  53723. * On center pick
  53724. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53725. */
  53726. get: function () {
  53727. return ActionManager._OnCenterPickTrigger;
  53728. },
  53729. enumerable: true,
  53730. configurable: true
  53731. });
  53732. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53733. /**
  53734. * On pick down
  53735. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53736. */
  53737. get: function () {
  53738. return ActionManager._OnPickDownTrigger;
  53739. },
  53740. enumerable: true,
  53741. configurable: true
  53742. });
  53743. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53744. /**
  53745. * On double pick
  53746. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53747. */
  53748. get: function () {
  53749. return ActionManager._OnDoublePickTrigger;
  53750. },
  53751. enumerable: true,
  53752. configurable: true
  53753. });
  53754. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53755. /**
  53756. * On pick up
  53757. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53758. */
  53759. get: function () {
  53760. return ActionManager._OnPickUpTrigger;
  53761. },
  53762. enumerable: true,
  53763. configurable: true
  53764. });
  53765. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53766. /**
  53767. * On pick out.
  53768. * This trigger will only be raised if you also declared a OnPickDown
  53769. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53770. */
  53771. get: function () {
  53772. return ActionManager._OnPickOutTrigger;
  53773. },
  53774. enumerable: true,
  53775. configurable: true
  53776. });
  53777. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53778. /**
  53779. * On long press
  53780. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53781. */
  53782. get: function () {
  53783. return ActionManager._OnLongPressTrigger;
  53784. },
  53785. enumerable: true,
  53786. configurable: true
  53787. });
  53788. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53789. /**
  53790. * On pointer over
  53791. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53792. */
  53793. get: function () {
  53794. return ActionManager._OnPointerOverTrigger;
  53795. },
  53796. enumerable: true,
  53797. configurable: true
  53798. });
  53799. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53800. /**
  53801. * On pointer out
  53802. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53803. */
  53804. get: function () {
  53805. return ActionManager._OnPointerOutTrigger;
  53806. },
  53807. enumerable: true,
  53808. configurable: true
  53809. });
  53810. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53811. /**
  53812. * On every frame
  53813. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53814. */
  53815. get: function () {
  53816. return ActionManager._OnEveryFrameTrigger;
  53817. },
  53818. enumerable: true,
  53819. configurable: true
  53820. });
  53821. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53822. /**
  53823. * On intersection enter
  53824. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53825. */
  53826. get: function () {
  53827. return ActionManager._OnIntersectionEnterTrigger;
  53828. },
  53829. enumerable: true,
  53830. configurable: true
  53831. });
  53832. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53833. /**
  53834. * On intersection exit
  53835. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53836. */
  53837. get: function () {
  53838. return ActionManager._OnIntersectionExitTrigger;
  53839. },
  53840. enumerable: true,
  53841. configurable: true
  53842. });
  53843. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53844. /**
  53845. * On key down
  53846. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53847. */
  53848. get: function () {
  53849. return ActionManager._OnKeyDownTrigger;
  53850. },
  53851. enumerable: true,
  53852. configurable: true
  53853. });
  53854. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53855. /**
  53856. * On key up
  53857. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53858. */
  53859. get: function () {
  53860. return ActionManager._OnKeyUpTrigger;
  53861. },
  53862. enumerable: true,
  53863. configurable: true
  53864. });
  53865. // Methods
  53866. /**
  53867. * Releases all associated resources
  53868. */
  53869. ActionManager.prototype.dispose = function () {
  53870. var index = this._scene._actionManagers.indexOf(this);
  53871. for (var i = 0; i < this.actions.length; i++) {
  53872. var action = this.actions[i];
  53873. ActionManager.Triggers[action.trigger]--;
  53874. if (ActionManager.Triggers[action.trigger] === 0) {
  53875. delete ActionManager.Triggers[action.trigger];
  53876. }
  53877. }
  53878. if (index > -1) {
  53879. this._scene._actionManagers.splice(index, 1);
  53880. }
  53881. };
  53882. /**
  53883. * Gets hosting scene
  53884. * @returns the hosting scene
  53885. */
  53886. ActionManager.prototype.getScene = function () {
  53887. return this._scene;
  53888. };
  53889. /**
  53890. * Does this action manager handles actions of any of the given triggers
  53891. * @param triggers defines the triggers to be tested
  53892. * @return a boolean indicating whether one (or more) of the triggers is handled
  53893. */
  53894. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53895. for (var index = 0; index < this.actions.length; index++) {
  53896. var action = this.actions[index];
  53897. if (triggers.indexOf(action.trigger) > -1) {
  53898. return true;
  53899. }
  53900. }
  53901. return false;
  53902. };
  53903. /**
  53904. * Does this action manager handles actions of a given trigger
  53905. * @param trigger defines the trigger to be tested
  53906. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53907. * @return whether the trigger is handled
  53908. */
  53909. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53910. for (var index = 0; index < this.actions.length; index++) {
  53911. var action = this.actions[index];
  53912. if (action.trigger === trigger) {
  53913. if (parameterPredicate) {
  53914. if (parameterPredicate(action.getTriggerParameter())) {
  53915. return true;
  53916. }
  53917. }
  53918. else {
  53919. return true;
  53920. }
  53921. }
  53922. }
  53923. return false;
  53924. };
  53925. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53926. /**
  53927. * Does this action manager has pointer triggers
  53928. */
  53929. get: function () {
  53930. for (var index = 0; index < this.actions.length; index++) {
  53931. var action = this.actions[index];
  53932. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53933. return true;
  53934. }
  53935. }
  53936. return false;
  53937. },
  53938. enumerable: true,
  53939. configurable: true
  53940. });
  53941. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53942. /**
  53943. * Does this action manager has pick triggers
  53944. */
  53945. get: function () {
  53946. for (var index = 0; index < this.actions.length; index++) {
  53947. var action = this.actions[index];
  53948. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53949. return true;
  53950. }
  53951. }
  53952. return false;
  53953. },
  53954. enumerable: true,
  53955. configurable: true
  53956. });
  53957. Object.defineProperty(ActionManager, "HasTriggers", {
  53958. /**
  53959. * Does exist one action manager with at least one trigger
  53960. **/
  53961. get: function () {
  53962. for (var t in ActionManager.Triggers) {
  53963. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53964. return true;
  53965. }
  53966. }
  53967. return false;
  53968. },
  53969. enumerable: true,
  53970. configurable: true
  53971. });
  53972. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53973. /**
  53974. * Does exist one action manager with at least one pick trigger
  53975. **/
  53976. get: function () {
  53977. for (var t in ActionManager.Triggers) {
  53978. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53979. var t_int = parseInt(t);
  53980. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53981. return true;
  53982. }
  53983. }
  53984. }
  53985. return false;
  53986. },
  53987. enumerable: true,
  53988. configurable: true
  53989. });
  53990. /**
  53991. * Does exist one action manager that handles actions of a given trigger
  53992. * @param trigger defines the trigger to be tested
  53993. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53994. **/
  53995. ActionManager.HasSpecificTrigger = function (trigger) {
  53996. for (var t in ActionManager.Triggers) {
  53997. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53998. var t_int = parseInt(t);
  53999. if (t_int === trigger) {
  54000. return true;
  54001. }
  54002. }
  54003. }
  54004. return false;
  54005. };
  54006. /**
  54007. * Registers an action to this action manager
  54008. * @param action defines the action to be registered
  54009. * @return the action amended (prepared) after registration
  54010. */
  54011. ActionManager.prototype.registerAction = function (action) {
  54012. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54013. if (this.getScene().actionManager !== this) {
  54014. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54015. return null;
  54016. }
  54017. }
  54018. this.actions.push(action);
  54019. if (ActionManager.Triggers[action.trigger]) {
  54020. ActionManager.Triggers[action.trigger]++;
  54021. }
  54022. else {
  54023. ActionManager.Triggers[action.trigger] = 1;
  54024. }
  54025. action._actionManager = this;
  54026. action._prepare();
  54027. return action;
  54028. };
  54029. /**
  54030. * Unregisters an action to this action manager
  54031. * @param action defines the action to be unregistered
  54032. * @return a boolean indicating whether the action has been unregistered
  54033. */
  54034. ActionManager.prototype.unregisterAction = function (action) {
  54035. var index = this.actions.indexOf(action);
  54036. if (index !== -1) {
  54037. this.actions.splice(index, 1);
  54038. ActionManager.Triggers[action.trigger] -= 1;
  54039. if (ActionManager.Triggers[action.trigger] === 0) {
  54040. delete ActionManager.Triggers[action.trigger];
  54041. }
  54042. delete action._actionManager;
  54043. return true;
  54044. }
  54045. return false;
  54046. };
  54047. /**
  54048. * Process a specific trigger
  54049. * @param trigger defines the trigger to process
  54050. * @param evt defines the event details to be processed
  54051. */
  54052. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54053. for (var index = 0; index < this.actions.length; index++) {
  54054. var action = this.actions[index];
  54055. if (action.trigger === trigger) {
  54056. if (evt) {
  54057. if (trigger === ActionManager.OnKeyUpTrigger
  54058. || trigger === ActionManager.OnKeyDownTrigger) {
  54059. var parameter = action.getTriggerParameter();
  54060. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54061. if (!parameter.toLowerCase) {
  54062. continue;
  54063. }
  54064. var lowerCase = parameter.toLowerCase();
  54065. if (lowerCase !== evt.sourceEvent.key) {
  54066. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54067. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54068. if (actualkey !== lowerCase) {
  54069. continue;
  54070. }
  54071. }
  54072. }
  54073. }
  54074. }
  54075. action._executeCurrent(evt);
  54076. }
  54077. }
  54078. };
  54079. /** @hidden */
  54080. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54081. var properties = propertyPath.split(".");
  54082. for (var index = 0; index < properties.length - 1; index++) {
  54083. target = target[properties[index]];
  54084. }
  54085. return target;
  54086. };
  54087. /** @hidden */
  54088. ActionManager.prototype._getProperty = function (propertyPath) {
  54089. var properties = propertyPath.split(".");
  54090. return properties[properties.length - 1];
  54091. };
  54092. /**
  54093. * Serialize this manager to a JSON object
  54094. * @param name defines the property name to store this manager
  54095. * @returns a JSON representation of this manager
  54096. */
  54097. ActionManager.prototype.serialize = function (name) {
  54098. var root = {
  54099. children: new Array(),
  54100. name: name,
  54101. type: 3,
  54102. properties: new Array() // Empty for root but required
  54103. };
  54104. for (var i = 0; i < this.actions.length; i++) {
  54105. var triggerObject = {
  54106. type: 0,
  54107. children: new Array(),
  54108. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54109. properties: new Array()
  54110. };
  54111. var triggerOptions = this.actions[i].triggerOptions;
  54112. if (triggerOptions && typeof triggerOptions !== "number") {
  54113. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54114. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54115. }
  54116. else {
  54117. var parameter = {};
  54118. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54119. if (triggerOptions.parameter.mesh) {
  54120. parameter._meshId = triggerOptions.parameter.mesh.id;
  54121. }
  54122. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54123. }
  54124. }
  54125. // Serialize child action, recursively
  54126. this.actions[i].serialize(triggerObject);
  54127. // Add serialized trigger
  54128. root.children.push(triggerObject);
  54129. }
  54130. return root;
  54131. };
  54132. /**
  54133. * Creates a new ActionManager from a JSON data
  54134. * @param parsedActions defines the JSON data to read from
  54135. * @param object defines the hosting mesh
  54136. * @param scene defines the hosting scene
  54137. */
  54138. ActionManager.Parse = function (parsedActions, object, scene) {
  54139. var actionManager = new ActionManager(scene);
  54140. if (object === null)
  54141. scene.actionManager = actionManager;
  54142. else
  54143. object.actionManager = actionManager;
  54144. // instanciate a new object
  54145. var instanciate = function (name, params) {
  54146. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54147. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54148. newInstance.constructor.apply(newInstance, params);
  54149. return newInstance;
  54150. };
  54151. var parseParameter = function (name, value, target, propertyPath) {
  54152. if (propertyPath === null) {
  54153. // String, boolean or float
  54154. var floatValue = parseFloat(value);
  54155. if (value === "true" || value === "false")
  54156. return value === "true";
  54157. else
  54158. return isNaN(floatValue) ? value : floatValue;
  54159. }
  54160. var effectiveTarget = propertyPath.split(".");
  54161. var values = value.split(",");
  54162. // Get effective Target
  54163. for (var i = 0; i < effectiveTarget.length; i++) {
  54164. target = target[effectiveTarget[i]];
  54165. }
  54166. // Return appropriate value with its type
  54167. if (typeof (target) === "boolean")
  54168. return values[0] === "true";
  54169. if (typeof (target) === "string")
  54170. return values[0];
  54171. // Parameters with multiple values such as Vector3 etc.
  54172. var split = new Array();
  54173. for (var i = 0; i < values.length; i++)
  54174. split.push(parseFloat(values[i]));
  54175. if (target instanceof BABYLON.Vector3)
  54176. return BABYLON.Vector3.FromArray(split);
  54177. if (target instanceof BABYLON.Vector4)
  54178. return BABYLON.Vector4.FromArray(split);
  54179. if (target instanceof BABYLON.Color3)
  54180. return BABYLON.Color3.FromArray(split);
  54181. if (target instanceof BABYLON.Color4)
  54182. return BABYLON.Color4.FromArray(split);
  54183. return parseFloat(values[0]);
  54184. };
  54185. // traverse graph per trigger
  54186. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54187. if (combineArray === void 0) { combineArray = null; }
  54188. if (parsedAction.detached)
  54189. return;
  54190. var parameters = new Array();
  54191. var target = null;
  54192. var propertyPath = null;
  54193. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54194. // Parameters
  54195. if (parsedAction.type === 2)
  54196. parameters.push(actionManager);
  54197. else
  54198. parameters.push(trigger);
  54199. if (combine) {
  54200. var actions = new Array();
  54201. for (var j = 0; j < parsedAction.combine.length; j++) {
  54202. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54203. }
  54204. parameters.push(actions);
  54205. }
  54206. else {
  54207. for (var i = 0; i < parsedAction.properties.length; i++) {
  54208. var value = parsedAction.properties[i].value;
  54209. var name = parsedAction.properties[i].name;
  54210. var targetType = parsedAction.properties[i].targetType;
  54211. if (name === "target")
  54212. if (targetType !== null && targetType === "SceneProperties")
  54213. value = target = scene;
  54214. else
  54215. value = target = scene.getNodeByName(value);
  54216. else if (name === "parent")
  54217. value = scene.getNodeByName(value);
  54218. else if (name === "sound")
  54219. value = scene.getSoundByName(value);
  54220. else if (name !== "propertyPath") {
  54221. if (parsedAction.type === 2 && name === "operator")
  54222. value = BABYLON.ValueCondition[value];
  54223. else
  54224. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54225. }
  54226. else {
  54227. propertyPath = value;
  54228. }
  54229. parameters.push(value);
  54230. }
  54231. }
  54232. if (combineArray === null) {
  54233. parameters.push(condition);
  54234. }
  54235. else {
  54236. parameters.push(null);
  54237. }
  54238. // If interpolate value action
  54239. if (parsedAction.name === "InterpolateValueAction") {
  54240. var param = parameters[parameters.length - 2];
  54241. parameters[parameters.length - 1] = param;
  54242. parameters[parameters.length - 2] = condition;
  54243. }
  54244. // Action or condition(s) and not CombineAction
  54245. var newAction = instanciate(parsedAction.name, parameters);
  54246. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54247. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54248. if (action)
  54249. action.then(nothing);
  54250. else
  54251. actionManager.registerAction(nothing);
  54252. action = nothing;
  54253. }
  54254. if (combineArray === null) {
  54255. if (newAction instanceof BABYLON.Condition) {
  54256. condition = newAction;
  54257. newAction = action;
  54258. }
  54259. else {
  54260. condition = null;
  54261. if (action)
  54262. action.then(newAction);
  54263. else
  54264. actionManager.registerAction(newAction);
  54265. }
  54266. }
  54267. else {
  54268. combineArray.push(newAction);
  54269. }
  54270. for (var i = 0; i < parsedAction.children.length; i++)
  54271. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54272. };
  54273. // triggers
  54274. for (var i = 0; i < parsedActions.children.length; i++) {
  54275. var triggerParams;
  54276. var trigger = parsedActions.children[i];
  54277. if (trigger.properties.length > 0) {
  54278. var param = trigger.properties[0].value;
  54279. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54280. if (value._meshId) {
  54281. value.mesh = scene.getMeshByID(value._meshId);
  54282. }
  54283. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54284. }
  54285. else
  54286. triggerParams = ActionManager[trigger.name];
  54287. for (var j = 0; j < trigger.children.length; j++) {
  54288. if (!trigger.detached)
  54289. traverse(trigger.children[j], triggerParams, null, null);
  54290. }
  54291. }
  54292. };
  54293. /**
  54294. * Get a trigger name by index
  54295. * @param trigger defines the trigger index
  54296. * @returns a trigger name
  54297. */
  54298. ActionManager.GetTriggerName = function (trigger) {
  54299. switch (trigger) {
  54300. case 0: return "NothingTrigger";
  54301. case 1: return "OnPickTrigger";
  54302. case 2: return "OnLeftPickTrigger";
  54303. case 3: return "OnRightPickTrigger";
  54304. case 4: return "OnCenterPickTrigger";
  54305. case 5: return "OnPickDownTrigger";
  54306. case 6: return "OnPickUpTrigger";
  54307. case 7: return "OnLongPressTrigger";
  54308. case 8: return "OnPointerOverTrigger";
  54309. case 9: return "OnPointerOutTrigger";
  54310. case 10: return "OnEveryFrameTrigger";
  54311. case 11: return "OnIntersectionEnterTrigger";
  54312. case 12: return "OnIntersectionExitTrigger";
  54313. case 13: return "OnKeyDownTrigger";
  54314. case 14: return "OnKeyUpTrigger";
  54315. case 15: return "OnPickOutTrigger";
  54316. default: return "";
  54317. }
  54318. };
  54319. // Statics
  54320. ActionManager._NothingTrigger = 0;
  54321. ActionManager._OnPickTrigger = 1;
  54322. ActionManager._OnLeftPickTrigger = 2;
  54323. ActionManager._OnRightPickTrigger = 3;
  54324. ActionManager._OnCenterPickTrigger = 4;
  54325. ActionManager._OnPickDownTrigger = 5;
  54326. ActionManager._OnDoublePickTrigger = 6;
  54327. ActionManager._OnPickUpTrigger = 7;
  54328. ActionManager._OnLongPressTrigger = 8;
  54329. ActionManager._OnPointerOverTrigger = 9;
  54330. ActionManager._OnPointerOutTrigger = 10;
  54331. ActionManager._OnEveryFrameTrigger = 11;
  54332. ActionManager._OnIntersectionEnterTrigger = 12;
  54333. ActionManager._OnIntersectionExitTrigger = 13;
  54334. ActionManager._OnKeyDownTrigger = 14;
  54335. ActionManager._OnKeyUpTrigger = 15;
  54336. ActionManager._OnPickOutTrigger = 16;
  54337. /** Gets the list of active triggers */
  54338. ActionManager.Triggers = {};
  54339. return ActionManager;
  54340. }());
  54341. BABYLON.ActionManager = ActionManager;
  54342. })(BABYLON || (BABYLON = {}));
  54343. //# sourceMappingURL=babylon.actionManager.js.map
  54344. var BABYLON;
  54345. (function (BABYLON) {
  54346. var InterpolateValueAction = /** @class */ (function (_super) {
  54347. __extends(InterpolateValueAction, _super);
  54348. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54349. if (duration === void 0) { duration = 1000; }
  54350. var _this = _super.call(this, triggerOptions, condition) || this;
  54351. _this.propertyPath = propertyPath;
  54352. _this.value = value;
  54353. _this.duration = duration;
  54354. _this.stopOtherAnimations = stopOtherAnimations;
  54355. _this.onInterpolationDone = onInterpolationDone;
  54356. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54357. _this._target = _this._effectiveTarget = target;
  54358. return _this;
  54359. }
  54360. InterpolateValueAction.prototype._prepare = function () {
  54361. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54362. this._property = this._getProperty(this.propertyPath);
  54363. };
  54364. InterpolateValueAction.prototype.execute = function () {
  54365. var _this = this;
  54366. var scene = this._actionManager.getScene();
  54367. var keys = [
  54368. {
  54369. frame: 0,
  54370. value: this._effectiveTarget[this._property]
  54371. }, {
  54372. frame: 100,
  54373. value: this.value
  54374. }
  54375. ];
  54376. var dataType;
  54377. if (typeof this.value === "number") {
  54378. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54379. }
  54380. else if (this.value instanceof BABYLON.Color3) {
  54381. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54382. }
  54383. else if (this.value instanceof BABYLON.Vector3) {
  54384. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54385. }
  54386. else if (this.value instanceof BABYLON.Matrix) {
  54387. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54388. }
  54389. else if (this.value instanceof BABYLON.Quaternion) {
  54390. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54391. }
  54392. else {
  54393. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54394. return;
  54395. }
  54396. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54397. animation.setKeys(keys);
  54398. if (this.stopOtherAnimations) {
  54399. scene.stopAnimation(this._effectiveTarget);
  54400. }
  54401. var wrapper = function () {
  54402. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54403. if (_this.onInterpolationDone) {
  54404. _this.onInterpolationDone();
  54405. }
  54406. };
  54407. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54408. };
  54409. InterpolateValueAction.prototype.serialize = function (parent) {
  54410. return _super.prototype._serialize.call(this, {
  54411. name: "InterpolateValueAction",
  54412. properties: [
  54413. BABYLON.Action._GetTargetProperty(this._target),
  54414. { name: "propertyPath", value: this.propertyPath },
  54415. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54416. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54417. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54418. ]
  54419. }, parent);
  54420. };
  54421. return InterpolateValueAction;
  54422. }(BABYLON.Action));
  54423. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54424. })(BABYLON || (BABYLON = {}));
  54425. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54426. var BABYLON;
  54427. (function (BABYLON) {
  54428. var SwitchBooleanAction = /** @class */ (function (_super) {
  54429. __extends(SwitchBooleanAction, _super);
  54430. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54431. var _this = _super.call(this, triggerOptions, condition) || this;
  54432. _this.propertyPath = propertyPath;
  54433. _this._target = _this._effectiveTarget = target;
  54434. return _this;
  54435. }
  54436. SwitchBooleanAction.prototype._prepare = function () {
  54437. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54438. this._property = this._getProperty(this.propertyPath);
  54439. };
  54440. SwitchBooleanAction.prototype.execute = function () {
  54441. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54442. };
  54443. SwitchBooleanAction.prototype.serialize = function (parent) {
  54444. return _super.prototype._serialize.call(this, {
  54445. name: "SwitchBooleanAction",
  54446. properties: [
  54447. BABYLON.Action._GetTargetProperty(this._target),
  54448. { name: "propertyPath", value: this.propertyPath }
  54449. ]
  54450. }, parent);
  54451. };
  54452. return SwitchBooleanAction;
  54453. }(BABYLON.Action));
  54454. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54455. var SetStateAction = /** @class */ (function (_super) {
  54456. __extends(SetStateAction, _super);
  54457. function SetStateAction(triggerOptions, target, value, condition) {
  54458. var _this = _super.call(this, triggerOptions, condition) || this;
  54459. _this.value = value;
  54460. _this._target = target;
  54461. return _this;
  54462. }
  54463. SetStateAction.prototype.execute = function () {
  54464. this._target.state = this.value;
  54465. };
  54466. SetStateAction.prototype.serialize = function (parent) {
  54467. return _super.prototype._serialize.call(this, {
  54468. name: "SetStateAction",
  54469. properties: [
  54470. BABYLON.Action._GetTargetProperty(this._target),
  54471. { name: "value", value: this.value }
  54472. ]
  54473. }, parent);
  54474. };
  54475. return SetStateAction;
  54476. }(BABYLON.Action));
  54477. BABYLON.SetStateAction = SetStateAction;
  54478. var SetValueAction = /** @class */ (function (_super) {
  54479. __extends(SetValueAction, _super);
  54480. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54481. var _this = _super.call(this, triggerOptions, condition) || this;
  54482. _this.propertyPath = propertyPath;
  54483. _this.value = value;
  54484. _this._target = _this._effectiveTarget = target;
  54485. return _this;
  54486. }
  54487. SetValueAction.prototype._prepare = function () {
  54488. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54489. this._property = this._getProperty(this.propertyPath);
  54490. };
  54491. SetValueAction.prototype.execute = function () {
  54492. this._effectiveTarget[this._property] = this.value;
  54493. if (this._target.markAsDirty) {
  54494. this._target.markAsDirty(this._property);
  54495. }
  54496. };
  54497. SetValueAction.prototype.serialize = function (parent) {
  54498. return _super.prototype._serialize.call(this, {
  54499. name: "SetValueAction",
  54500. properties: [
  54501. BABYLON.Action._GetTargetProperty(this._target),
  54502. { name: "propertyPath", value: this.propertyPath },
  54503. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54504. ]
  54505. }, parent);
  54506. };
  54507. return SetValueAction;
  54508. }(BABYLON.Action));
  54509. BABYLON.SetValueAction = SetValueAction;
  54510. var IncrementValueAction = /** @class */ (function (_super) {
  54511. __extends(IncrementValueAction, _super);
  54512. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54513. var _this = _super.call(this, triggerOptions, condition) || this;
  54514. _this.propertyPath = propertyPath;
  54515. _this.value = value;
  54516. _this._target = _this._effectiveTarget = target;
  54517. return _this;
  54518. }
  54519. IncrementValueAction.prototype._prepare = function () {
  54520. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54521. this._property = this._getProperty(this.propertyPath);
  54522. if (typeof this._effectiveTarget[this._property] !== "number") {
  54523. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54524. }
  54525. };
  54526. IncrementValueAction.prototype.execute = function () {
  54527. this._effectiveTarget[this._property] += this.value;
  54528. if (this._target.markAsDirty) {
  54529. this._target.markAsDirty(this._property);
  54530. }
  54531. };
  54532. IncrementValueAction.prototype.serialize = function (parent) {
  54533. return _super.prototype._serialize.call(this, {
  54534. name: "IncrementValueAction",
  54535. properties: [
  54536. BABYLON.Action._GetTargetProperty(this._target),
  54537. { name: "propertyPath", value: this.propertyPath },
  54538. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54539. ]
  54540. }, parent);
  54541. };
  54542. return IncrementValueAction;
  54543. }(BABYLON.Action));
  54544. BABYLON.IncrementValueAction = IncrementValueAction;
  54545. var PlayAnimationAction = /** @class */ (function (_super) {
  54546. __extends(PlayAnimationAction, _super);
  54547. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54548. var _this = _super.call(this, triggerOptions, condition) || this;
  54549. _this.from = from;
  54550. _this.to = to;
  54551. _this.loop = loop;
  54552. _this._target = target;
  54553. return _this;
  54554. }
  54555. PlayAnimationAction.prototype._prepare = function () {
  54556. };
  54557. PlayAnimationAction.prototype.execute = function () {
  54558. var scene = this._actionManager.getScene();
  54559. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54560. };
  54561. PlayAnimationAction.prototype.serialize = function (parent) {
  54562. return _super.prototype._serialize.call(this, {
  54563. name: "PlayAnimationAction",
  54564. properties: [
  54565. BABYLON.Action._GetTargetProperty(this._target),
  54566. { name: "from", value: String(this.from) },
  54567. { name: "to", value: String(this.to) },
  54568. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54569. ]
  54570. }, parent);
  54571. };
  54572. return PlayAnimationAction;
  54573. }(BABYLON.Action));
  54574. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54575. var StopAnimationAction = /** @class */ (function (_super) {
  54576. __extends(StopAnimationAction, _super);
  54577. function StopAnimationAction(triggerOptions, target, condition) {
  54578. var _this = _super.call(this, triggerOptions, condition) || this;
  54579. _this._target = target;
  54580. return _this;
  54581. }
  54582. StopAnimationAction.prototype._prepare = function () {
  54583. };
  54584. StopAnimationAction.prototype.execute = function () {
  54585. var scene = this._actionManager.getScene();
  54586. scene.stopAnimation(this._target);
  54587. };
  54588. StopAnimationAction.prototype.serialize = function (parent) {
  54589. return _super.prototype._serialize.call(this, {
  54590. name: "StopAnimationAction",
  54591. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54592. }, parent);
  54593. };
  54594. return StopAnimationAction;
  54595. }(BABYLON.Action));
  54596. BABYLON.StopAnimationAction = StopAnimationAction;
  54597. var DoNothingAction = /** @class */ (function (_super) {
  54598. __extends(DoNothingAction, _super);
  54599. function DoNothingAction(triggerOptions, condition) {
  54600. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54601. return _super.call(this, triggerOptions, condition) || this;
  54602. }
  54603. DoNothingAction.prototype.execute = function () {
  54604. };
  54605. DoNothingAction.prototype.serialize = function (parent) {
  54606. return _super.prototype._serialize.call(this, {
  54607. name: "DoNothingAction",
  54608. properties: []
  54609. }, parent);
  54610. };
  54611. return DoNothingAction;
  54612. }(BABYLON.Action));
  54613. BABYLON.DoNothingAction = DoNothingAction;
  54614. var CombineAction = /** @class */ (function (_super) {
  54615. __extends(CombineAction, _super);
  54616. function CombineAction(triggerOptions, children, condition) {
  54617. var _this = _super.call(this, triggerOptions, condition) || this;
  54618. _this.children = children;
  54619. return _this;
  54620. }
  54621. CombineAction.prototype._prepare = function () {
  54622. for (var index = 0; index < this.children.length; index++) {
  54623. this.children[index]._actionManager = this._actionManager;
  54624. this.children[index]._prepare();
  54625. }
  54626. };
  54627. CombineAction.prototype.execute = function (evt) {
  54628. for (var index = 0; index < this.children.length; index++) {
  54629. this.children[index].execute(evt);
  54630. }
  54631. };
  54632. CombineAction.prototype.serialize = function (parent) {
  54633. var serializationObject = _super.prototype._serialize.call(this, {
  54634. name: "CombineAction",
  54635. properties: [],
  54636. combine: []
  54637. }, parent);
  54638. for (var i = 0; i < this.children.length; i++) {
  54639. serializationObject.combine.push(this.children[i].serialize(null));
  54640. }
  54641. return serializationObject;
  54642. };
  54643. return CombineAction;
  54644. }(BABYLON.Action));
  54645. BABYLON.CombineAction = CombineAction;
  54646. var ExecuteCodeAction = /** @class */ (function (_super) {
  54647. __extends(ExecuteCodeAction, _super);
  54648. function ExecuteCodeAction(triggerOptions, func, condition) {
  54649. var _this = _super.call(this, triggerOptions, condition) || this;
  54650. _this.func = func;
  54651. return _this;
  54652. }
  54653. ExecuteCodeAction.prototype.execute = function (evt) {
  54654. this.func(evt);
  54655. };
  54656. return ExecuteCodeAction;
  54657. }(BABYLON.Action));
  54658. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54659. var SetParentAction = /** @class */ (function (_super) {
  54660. __extends(SetParentAction, _super);
  54661. function SetParentAction(triggerOptions, target, parent, condition) {
  54662. var _this = _super.call(this, triggerOptions, condition) || this;
  54663. _this._target = target;
  54664. _this._parent = parent;
  54665. return _this;
  54666. }
  54667. SetParentAction.prototype._prepare = function () {
  54668. };
  54669. SetParentAction.prototype.execute = function () {
  54670. if (this._target.parent === this._parent) {
  54671. return;
  54672. }
  54673. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54674. invertParentWorldMatrix.invert();
  54675. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54676. this._target.parent = this._parent;
  54677. };
  54678. SetParentAction.prototype.serialize = function (parent) {
  54679. return _super.prototype._serialize.call(this, {
  54680. name: "SetParentAction",
  54681. properties: [
  54682. BABYLON.Action._GetTargetProperty(this._target),
  54683. BABYLON.Action._GetTargetProperty(this._parent),
  54684. ]
  54685. }, parent);
  54686. };
  54687. return SetParentAction;
  54688. }(BABYLON.Action));
  54689. BABYLON.SetParentAction = SetParentAction;
  54690. var PlaySoundAction = /** @class */ (function (_super) {
  54691. __extends(PlaySoundAction, _super);
  54692. function PlaySoundAction(triggerOptions, sound, condition) {
  54693. var _this = _super.call(this, triggerOptions, condition) || this;
  54694. _this._sound = sound;
  54695. return _this;
  54696. }
  54697. PlaySoundAction.prototype._prepare = function () {
  54698. };
  54699. PlaySoundAction.prototype.execute = function () {
  54700. if (this._sound !== undefined)
  54701. this._sound.play();
  54702. };
  54703. PlaySoundAction.prototype.serialize = function (parent) {
  54704. return _super.prototype._serialize.call(this, {
  54705. name: "PlaySoundAction",
  54706. properties: [{ name: "sound", value: this._sound.name }]
  54707. }, parent);
  54708. };
  54709. return PlaySoundAction;
  54710. }(BABYLON.Action));
  54711. BABYLON.PlaySoundAction = PlaySoundAction;
  54712. var StopSoundAction = /** @class */ (function (_super) {
  54713. __extends(StopSoundAction, _super);
  54714. function StopSoundAction(triggerOptions, sound, condition) {
  54715. var _this = _super.call(this, triggerOptions, condition) || this;
  54716. _this._sound = sound;
  54717. return _this;
  54718. }
  54719. StopSoundAction.prototype._prepare = function () {
  54720. };
  54721. StopSoundAction.prototype.execute = function () {
  54722. if (this._sound !== undefined)
  54723. this._sound.stop();
  54724. };
  54725. StopSoundAction.prototype.serialize = function (parent) {
  54726. return _super.prototype._serialize.call(this, {
  54727. name: "StopSoundAction",
  54728. properties: [{ name: "sound", value: this._sound.name }]
  54729. }, parent);
  54730. };
  54731. return StopSoundAction;
  54732. }(BABYLON.Action));
  54733. BABYLON.StopSoundAction = StopSoundAction;
  54734. })(BABYLON || (BABYLON = {}));
  54735. //# sourceMappingURL=babylon.directActions.js.map
  54736. var BABYLON;
  54737. (function (BABYLON) {
  54738. var SpriteManager = /** @class */ (function () {
  54739. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54740. if (epsilon === void 0) { epsilon = 0.01; }
  54741. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54742. this.name = name;
  54743. this.sprites = new Array();
  54744. this.renderingGroupId = 0;
  54745. this.layerMask = 0x0FFFFFFF;
  54746. this.fogEnabled = true;
  54747. this.isPickable = false;
  54748. /**
  54749. * An event triggered when the manager is disposed.
  54750. */
  54751. this.onDisposeObservable = new BABYLON.Observable();
  54752. this._vertexBuffers = {};
  54753. this._capacity = capacity;
  54754. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54755. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54756. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54757. if (cellSize.width && cellSize.height) {
  54758. this.cellWidth = cellSize.width;
  54759. this.cellHeight = cellSize.height;
  54760. }
  54761. else if (cellSize !== undefined) {
  54762. this.cellWidth = cellSize;
  54763. this.cellHeight = cellSize;
  54764. }
  54765. else {
  54766. return;
  54767. }
  54768. this._epsilon = epsilon;
  54769. this._scene = scene;
  54770. this._scene.spriteManagers.push(this);
  54771. var indices = [];
  54772. var index = 0;
  54773. for (var count = 0; count < capacity; count++) {
  54774. indices.push(index);
  54775. indices.push(index + 1);
  54776. indices.push(index + 2);
  54777. indices.push(index);
  54778. indices.push(index + 2);
  54779. indices.push(index + 3);
  54780. index += 4;
  54781. }
  54782. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54783. // VBO
  54784. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54785. this._vertexData = new Float32Array(capacity * 16 * 4);
  54786. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54787. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54788. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54789. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54790. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54791. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54792. this._vertexBuffers["options"] = options;
  54793. this._vertexBuffers["cellInfo"] = cellInfo;
  54794. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54795. // Effects
  54796. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54797. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54798. }
  54799. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54800. set: function (callback) {
  54801. if (this._onDisposeObserver) {
  54802. this.onDisposeObservable.remove(this._onDisposeObserver);
  54803. }
  54804. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54805. },
  54806. enumerable: true,
  54807. configurable: true
  54808. });
  54809. Object.defineProperty(SpriteManager.prototype, "texture", {
  54810. get: function () {
  54811. return this._spriteTexture;
  54812. },
  54813. set: function (value) {
  54814. this._spriteTexture = value;
  54815. },
  54816. enumerable: true,
  54817. configurable: true
  54818. });
  54819. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54820. var arrayOffset = index * 16;
  54821. if (offsetX === 0)
  54822. offsetX = this._epsilon;
  54823. else if (offsetX === 1)
  54824. offsetX = 1 - this._epsilon;
  54825. if (offsetY === 0)
  54826. offsetY = this._epsilon;
  54827. else if (offsetY === 1)
  54828. offsetY = 1 - this._epsilon;
  54829. this._vertexData[arrayOffset] = sprite.position.x;
  54830. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54831. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54832. this._vertexData[arrayOffset + 3] = sprite.angle;
  54833. this._vertexData[arrayOffset + 4] = sprite.width;
  54834. this._vertexData[arrayOffset + 5] = sprite.height;
  54835. this._vertexData[arrayOffset + 6] = offsetX;
  54836. this._vertexData[arrayOffset + 7] = offsetY;
  54837. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54838. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54839. var offset = (sprite.cellIndex / rowSize) >> 0;
  54840. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54841. this._vertexData[arrayOffset + 11] = offset;
  54842. // Color
  54843. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54844. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54845. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54846. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54847. };
  54848. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54849. var count = Math.min(this._capacity, this.sprites.length);
  54850. var min = BABYLON.Vector3.Zero();
  54851. var max = BABYLON.Vector3.Zero();
  54852. var distance = Number.MAX_VALUE;
  54853. var currentSprite = null;
  54854. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54855. var cameraView = camera.getViewMatrix();
  54856. for (var index = 0; index < count; index++) {
  54857. var sprite = this.sprites[index];
  54858. if (!sprite) {
  54859. continue;
  54860. }
  54861. if (predicate) {
  54862. if (!predicate(sprite)) {
  54863. continue;
  54864. }
  54865. }
  54866. else if (!sprite.isPickable) {
  54867. continue;
  54868. }
  54869. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54870. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54871. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54872. if (ray.intersectsBoxMinMax(min, max)) {
  54873. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54874. if (distance > currentDistance) {
  54875. distance = currentDistance;
  54876. currentSprite = sprite;
  54877. if (fastCheck) {
  54878. break;
  54879. }
  54880. }
  54881. }
  54882. }
  54883. if (currentSprite) {
  54884. var result = new BABYLON.PickingInfo();
  54885. result.hit = true;
  54886. result.pickedSprite = currentSprite;
  54887. result.distance = distance;
  54888. return result;
  54889. }
  54890. return null;
  54891. };
  54892. SpriteManager.prototype.render = function () {
  54893. // Check
  54894. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54895. return;
  54896. var engine = this._scene.getEngine();
  54897. var baseSize = this._spriteTexture.getBaseSize();
  54898. // Sprites
  54899. var deltaTime = engine.getDeltaTime();
  54900. var max = Math.min(this._capacity, this.sprites.length);
  54901. var rowSize = baseSize.width / this.cellWidth;
  54902. var offset = 0;
  54903. for (var index = 0; index < max; index++) {
  54904. var sprite = this.sprites[index];
  54905. if (!sprite) {
  54906. continue;
  54907. }
  54908. sprite._animate(deltaTime);
  54909. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54910. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54911. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54912. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54913. }
  54914. this._buffer.update(this._vertexData);
  54915. // Render
  54916. var effect = this._effectBase;
  54917. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54918. effect = this._effectFog;
  54919. }
  54920. engine.enableEffect(effect);
  54921. var viewMatrix = this._scene.getViewMatrix();
  54922. effect.setTexture("diffuseSampler", this._spriteTexture);
  54923. effect.setMatrix("view", viewMatrix);
  54924. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54925. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54926. // Fog
  54927. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54928. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54929. effect.setColor3("vFogColor", this._scene.fogColor);
  54930. }
  54931. // VBOs
  54932. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54933. // Draw order
  54934. engine.setDepthFunctionToLessOrEqual();
  54935. effect.setBool("alphaTest", true);
  54936. engine.setColorWrite(false);
  54937. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54938. engine.setColorWrite(true);
  54939. effect.setBool("alphaTest", false);
  54940. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54941. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54942. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54943. };
  54944. SpriteManager.prototype.dispose = function () {
  54945. if (this._buffer) {
  54946. this._buffer.dispose();
  54947. this._buffer = null;
  54948. }
  54949. if (this._indexBuffer) {
  54950. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54951. this._indexBuffer = null;
  54952. }
  54953. if (this._spriteTexture) {
  54954. this._spriteTexture.dispose();
  54955. this._spriteTexture = null;
  54956. }
  54957. // Remove from scene
  54958. var index = this._scene.spriteManagers.indexOf(this);
  54959. this._scene.spriteManagers.splice(index, 1);
  54960. // Callback
  54961. this.onDisposeObservable.notifyObservers(this);
  54962. this.onDisposeObservable.clear();
  54963. };
  54964. return SpriteManager;
  54965. }());
  54966. BABYLON.SpriteManager = SpriteManager;
  54967. })(BABYLON || (BABYLON = {}));
  54968. //# sourceMappingURL=babylon.spriteManager.js.map
  54969. var BABYLON;
  54970. (function (BABYLON) {
  54971. var Sprite = /** @class */ (function () {
  54972. function Sprite(name, manager) {
  54973. this.name = name;
  54974. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54975. this.width = 1.0;
  54976. this.height = 1.0;
  54977. this.angle = 0;
  54978. this.cellIndex = 0;
  54979. this.invertU = 0;
  54980. this.invertV = 0;
  54981. this.animations = new Array();
  54982. this.isPickable = false;
  54983. this._animationStarted = false;
  54984. this._loopAnimation = false;
  54985. this._fromIndex = 0;
  54986. this._toIndex = 0;
  54987. this._delay = 0;
  54988. this._direction = 1;
  54989. this._time = 0;
  54990. this._manager = manager;
  54991. this._manager.sprites.push(this);
  54992. this.position = BABYLON.Vector3.Zero();
  54993. }
  54994. Object.defineProperty(Sprite.prototype, "size", {
  54995. get: function () {
  54996. return this.width;
  54997. },
  54998. set: function (value) {
  54999. this.width = value;
  55000. this.height = value;
  55001. },
  55002. enumerable: true,
  55003. configurable: true
  55004. });
  55005. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55006. this._fromIndex = from;
  55007. this._toIndex = to;
  55008. this._loopAnimation = loop;
  55009. this._delay = delay;
  55010. this._animationStarted = true;
  55011. this._direction = from < to ? 1 : -1;
  55012. this.cellIndex = from;
  55013. this._time = 0;
  55014. this._onAnimationEnd = onAnimationEnd;
  55015. };
  55016. Sprite.prototype.stopAnimation = function () {
  55017. this._animationStarted = false;
  55018. };
  55019. Sprite.prototype._animate = function (deltaTime) {
  55020. if (!this._animationStarted)
  55021. return;
  55022. this._time += deltaTime;
  55023. if (this._time > this._delay) {
  55024. this._time = this._time % this._delay;
  55025. this.cellIndex += this._direction;
  55026. if (this.cellIndex > this._toIndex) {
  55027. if (this._loopAnimation) {
  55028. this.cellIndex = this._fromIndex;
  55029. }
  55030. else {
  55031. this.cellIndex = this._toIndex;
  55032. this._animationStarted = false;
  55033. if (this._onAnimationEnd) {
  55034. this._onAnimationEnd();
  55035. }
  55036. if (this.disposeWhenFinishedAnimating) {
  55037. this.dispose();
  55038. }
  55039. }
  55040. }
  55041. }
  55042. };
  55043. Sprite.prototype.dispose = function () {
  55044. for (var i = 0; i < this._manager.sprites.length; i++) {
  55045. if (this._manager.sprites[i] == this) {
  55046. this._manager.sprites.splice(i, 1);
  55047. }
  55048. }
  55049. };
  55050. return Sprite;
  55051. }());
  55052. BABYLON.Sprite = Sprite;
  55053. })(BABYLON || (BABYLON = {}));
  55054. //# sourceMappingURL=babylon.sprite.js.map
  55055. var BABYLON;
  55056. (function (BABYLON) {
  55057. var IntersectionInfo = /** @class */ (function () {
  55058. function IntersectionInfo(bu, bv, distance) {
  55059. this.bu = bu;
  55060. this.bv = bv;
  55061. this.distance = distance;
  55062. this.faceId = 0;
  55063. this.subMeshId = 0;
  55064. }
  55065. return IntersectionInfo;
  55066. }());
  55067. BABYLON.IntersectionInfo = IntersectionInfo;
  55068. /**
  55069. * Information about the result of picking within a scene
  55070. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55071. */
  55072. var PickingInfo = /** @class */ (function () {
  55073. function PickingInfo() {
  55074. /**
  55075. * If the pick collided with an object
  55076. */
  55077. this.hit = false;
  55078. /**
  55079. * Distance away where the pick collided
  55080. */
  55081. this.distance = 0;
  55082. /**
  55083. * The location of pick collision
  55084. */
  55085. this.pickedPoint = null;
  55086. /**
  55087. * The mesh corrisponding the the pick collision
  55088. */
  55089. this.pickedMesh = null;
  55090. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55091. this.bu = 0;
  55092. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55093. this.bv = 0;
  55094. /** The id of the face on the mesh that was picked */
  55095. this.faceId = -1;
  55096. /** Id of the the submesh that was picked */
  55097. this.subMeshId = 0;
  55098. /** If a sprite was picked, this will be the sprite the pick collided with */
  55099. this.pickedSprite = null;
  55100. /**
  55101. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55102. */
  55103. this.originMesh = null;
  55104. /**
  55105. * The ray that was used to perform the picking.
  55106. */
  55107. this.ray = null;
  55108. }
  55109. /**
  55110. * Gets the normal corrispodning to the face the pick collided with
  55111. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55112. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55113. * @returns The normal corrispodning to the face the pick collided with
  55114. */
  55115. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55116. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55117. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55118. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55119. return null;
  55120. }
  55121. var indices = this.pickedMesh.getIndices();
  55122. if (!indices) {
  55123. return null;
  55124. }
  55125. var result;
  55126. if (useVerticesNormals) {
  55127. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55128. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55129. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55130. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55131. normal0 = normal0.scale(this.bu);
  55132. normal1 = normal1.scale(this.bv);
  55133. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55134. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55135. }
  55136. else {
  55137. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55138. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55139. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55140. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55141. var p1p2 = vertex1.subtract(vertex2);
  55142. var p3p2 = vertex3.subtract(vertex2);
  55143. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55144. }
  55145. if (useWorldCoordinates) {
  55146. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55147. }
  55148. return BABYLON.Vector3.Normalize(result);
  55149. };
  55150. /**
  55151. * Gets the texture coordinates of where the pick occured
  55152. * @returns the vector containing the coordnates of the texture
  55153. */
  55154. PickingInfo.prototype.getTextureCoordinates = function () {
  55155. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55156. return null;
  55157. }
  55158. var indices = this.pickedMesh.getIndices();
  55159. if (!indices) {
  55160. return null;
  55161. }
  55162. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55163. if (!uvs) {
  55164. return null;
  55165. }
  55166. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55167. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55168. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55169. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55170. uv1 = uv1.scale(this.bu);
  55171. uv2 = uv2.scale(this.bv);
  55172. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55173. };
  55174. return PickingInfo;
  55175. }());
  55176. BABYLON.PickingInfo = PickingInfo;
  55177. })(BABYLON || (BABYLON = {}));
  55178. //# sourceMappingURL=babylon.pickingInfo.js.map
  55179. var BABYLON;
  55180. (function (BABYLON) {
  55181. var Ray = /** @class */ (function () {
  55182. function Ray(origin, direction, length) {
  55183. if (length === void 0) { length = Number.MAX_VALUE; }
  55184. this.origin = origin;
  55185. this.direction = direction;
  55186. this.length = length;
  55187. }
  55188. // Methods
  55189. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55190. var d = 0.0;
  55191. var maxValue = Number.MAX_VALUE;
  55192. var inv;
  55193. var min;
  55194. var max;
  55195. var temp;
  55196. if (Math.abs(this.direction.x) < 0.0000001) {
  55197. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55198. return false;
  55199. }
  55200. }
  55201. else {
  55202. inv = 1.0 / this.direction.x;
  55203. min = (minimum.x - this.origin.x) * inv;
  55204. max = (maximum.x - this.origin.x) * inv;
  55205. if (max === -Infinity) {
  55206. max = Infinity;
  55207. }
  55208. if (min > max) {
  55209. temp = min;
  55210. min = max;
  55211. max = temp;
  55212. }
  55213. d = Math.max(min, d);
  55214. maxValue = Math.min(max, maxValue);
  55215. if (d > maxValue) {
  55216. return false;
  55217. }
  55218. }
  55219. if (Math.abs(this.direction.y) < 0.0000001) {
  55220. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55221. return false;
  55222. }
  55223. }
  55224. else {
  55225. inv = 1.0 / this.direction.y;
  55226. min = (minimum.y - this.origin.y) * inv;
  55227. max = (maximum.y - this.origin.y) * inv;
  55228. if (max === -Infinity) {
  55229. max = Infinity;
  55230. }
  55231. if (min > max) {
  55232. temp = min;
  55233. min = max;
  55234. max = temp;
  55235. }
  55236. d = Math.max(min, d);
  55237. maxValue = Math.min(max, maxValue);
  55238. if (d > maxValue) {
  55239. return false;
  55240. }
  55241. }
  55242. if (Math.abs(this.direction.z) < 0.0000001) {
  55243. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55244. return false;
  55245. }
  55246. }
  55247. else {
  55248. inv = 1.0 / this.direction.z;
  55249. min = (minimum.z - this.origin.z) * inv;
  55250. max = (maximum.z - this.origin.z) * inv;
  55251. if (max === -Infinity) {
  55252. max = Infinity;
  55253. }
  55254. if (min > max) {
  55255. temp = min;
  55256. min = max;
  55257. max = temp;
  55258. }
  55259. d = Math.max(min, d);
  55260. maxValue = Math.min(max, maxValue);
  55261. if (d > maxValue) {
  55262. return false;
  55263. }
  55264. }
  55265. return true;
  55266. };
  55267. Ray.prototype.intersectsBox = function (box) {
  55268. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55269. };
  55270. Ray.prototype.intersectsSphere = function (sphere) {
  55271. var x = sphere.center.x - this.origin.x;
  55272. var y = sphere.center.y - this.origin.y;
  55273. var z = sphere.center.z - this.origin.z;
  55274. var pyth = (x * x) + (y * y) + (z * z);
  55275. var rr = sphere.radius * sphere.radius;
  55276. if (pyth <= rr) {
  55277. return true;
  55278. }
  55279. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55280. if (dot < 0.0) {
  55281. return false;
  55282. }
  55283. var temp = pyth - (dot * dot);
  55284. return temp <= rr;
  55285. };
  55286. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55287. if (!this._edge1) {
  55288. this._edge1 = BABYLON.Vector3.Zero();
  55289. this._edge2 = BABYLON.Vector3.Zero();
  55290. this._pvec = BABYLON.Vector3.Zero();
  55291. this._tvec = BABYLON.Vector3.Zero();
  55292. this._qvec = BABYLON.Vector3.Zero();
  55293. }
  55294. vertex1.subtractToRef(vertex0, this._edge1);
  55295. vertex2.subtractToRef(vertex0, this._edge2);
  55296. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55297. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55298. if (det === 0) {
  55299. return null;
  55300. }
  55301. var invdet = 1 / det;
  55302. this.origin.subtractToRef(vertex0, this._tvec);
  55303. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55304. if (bu < 0 || bu > 1.0) {
  55305. return null;
  55306. }
  55307. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55308. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55309. if (bv < 0 || bu + bv > 1.0) {
  55310. return null;
  55311. }
  55312. //check if the distance is longer than the predefined length.
  55313. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55314. if (distance > this.length) {
  55315. return null;
  55316. }
  55317. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55318. };
  55319. Ray.prototype.intersectsPlane = function (plane) {
  55320. var distance;
  55321. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55322. if (Math.abs(result1) < 9.99999997475243E-07) {
  55323. return null;
  55324. }
  55325. else {
  55326. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55327. distance = (-plane.d - result2) / result1;
  55328. if (distance < 0.0) {
  55329. if (distance < -9.99999997475243E-07) {
  55330. return null;
  55331. }
  55332. else {
  55333. return 0;
  55334. }
  55335. }
  55336. return distance;
  55337. }
  55338. };
  55339. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55340. var tm = BABYLON.Tmp.Matrix[0];
  55341. mesh.getWorldMatrix().invertToRef(tm);
  55342. if (this._tmpRay) {
  55343. Ray.TransformToRef(this, tm, this._tmpRay);
  55344. }
  55345. else {
  55346. this._tmpRay = Ray.Transform(this, tm);
  55347. }
  55348. return mesh.intersects(this._tmpRay, fastCheck);
  55349. };
  55350. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55351. if (results) {
  55352. results.length = 0;
  55353. }
  55354. else {
  55355. results = [];
  55356. }
  55357. for (var i = 0; i < meshes.length; i++) {
  55358. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55359. if (pickInfo.hit) {
  55360. results.push(pickInfo);
  55361. }
  55362. }
  55363. results.sort(this._comparePickingInfo);
  55364. return results;
  55365. };
  55366. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55367. if (pickingInfoA.distance < pickingInfoB.distance) {
  55368. return -1;
  55369. }
  55370. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55371. return 1;
  55372. }
  55373. else {
  55374. return 0;
  55375. }
  55376. };
  55377. /**
  55378. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55379. * @param sega the first point of the segment to test the intersection against
  55380. * @param segb the second point of the segment to test the intersection against
  55381. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55382. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55383. */
  55384. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55385. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55386. var u = segb.subtract(sega);
  55387. var v = rsegb.subtract(this.origin);
  55388. var w = sega.subtract(this.origin);
  55389. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55390. var b = BABYLON.Vector3.Dot(u, v);
  55391. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55392. var d = BABYLON.Vector3.Dot(u, w);
  55393. var e = BABYLON.Vector3.Dot(v, w);
  55394. var D = a * c - b * b; // always >= 0
  55395. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55396. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55397. // compute the line parameters of the two closest points
  55398. if (D < Ray.smallnum) { // the lines are almost parallel
  55399. sN = 0.0; // force using point P0 on segment S1
  55400. sD = 1.0; // to prevent possible division by 0.0 later
  55401. tN = e;
  55402. tD = c;
  55403. }
  55404. else { // get the closest points on the infinite lines
  55405. sN = (b * e - c * d);
  55406. tN = (a * e - b * d);
  55407. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55408. sN = 0.0;
  55409. tN = e;
  55410. tD = c;
  55411. }
  55412. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55413. sN = sD;
  55414. tN = e + b;
  55415. tD = c;
  55416. }
  55417. }
  55418. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55419. tN = 0.0;
  55420. // recompute sc for this edge
  55421. if (-d < 0.0) {
  55422. sN = 0.0;
  55423. }
  55424. else if (-d > a)
  55425. sN = sD;
  55426. else {
  55427. sN = -d;
  55428. sD = a;
  55429. }
  55430. }
  55431. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55432. tN = tD;
  55433. // recompute sc for this edge
  55434. if ((-d + b) < 0.0) {
  55435. sN = 0;
  55436. }
  55437. else if ((-d + b) > a) {
  55438. sN = sD;
  55439. }
  55440. else {
  55441. sN = (-d + b);
  55442. sD = a;
  55443. }
  55444. }
  55445. // finally do the division to get sc and tc
  55446. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55447. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55448. // get the difference of the two closest points
  55449. var qtc = v.multiplyByFloats(tc, tc, tc);
  55450. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55451. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55452. if (isIntersected) {
  55453. return qtc.length();
  55454. }
  55455. return -1;
  55456. };
  55457. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55458. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55459. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55460. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55461. this.direction.normalize();
  55462. return this;
  55463. };
  55464. // Statics
  55465. Ray.Zero = function () {
  55466. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55467. };
  55468. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55469. var result = Ray.Zero();
  55470. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55471. };
  55472. /**
  55473. * 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
  55474. * transformed to the given world matrix.
  55475. * @param origin The origin point
  55476. * @param end The end point
  55477. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55478. */
  55479. Ray.CreateNewFromTo = function (origin, end, world) {
  55480. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55481. var direction = end.subtract(origin);
  55482. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55483. direction.normalize();
  55484. return Ray.Transform(new Ray(origin, direction, length), world);
  55485. };
  55486. Ray.Transform = function (ray, matrix) {
  55487. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55488. Ray.TransformToRef(ray, matrix, result);
  55489. return result;
  55490. };
  55491. Ray.TransformToRef = function (ray, matrix, result) {
  55492. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55493. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55494. result.length = ray.length;
  55495. var dir = result.direction;
  55496. var len = dir.length();
  55497. if (!(len === 0 || len === 1)) {
  55498. var num = 1.0 / len;
  55499. dir.x *= num;
  55500. dir.y *= num;
  55501. dir.z *= num;
  55502. result.length *= len;
  55503. }
  55504. };
  55505. Ray.smallnum = 0.00000001;
  55506. Ray.rayl = 10e8;
  55507. return Ray;
  55508. }());
  55509. BABYLON.Ray = Ray;
  55510. })(BABYLON || (BABYLON = {}));
  55511. //# sourceMappingURL=babylon.ray.js.map
  55512. var BABYLON;
  55513. (function (BABYLON) {
  55514. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55515. if (boxMin.x > sphereCenter.x + sphereRadius)
  55516. return false;
  55517. if (sphereCenter.x - sphereRadius > boxMax.x)
  55518. return false;
  55519. if (boxMin.y > sphereCenter.y + sphereRadius)
  55520. return false;
  55521. if (sphereCenter.y - sphereRadius > boxMax.y)
  55522. return false;
  55523. if (boxMin.z > sphereCenter.z + sphereRadius)
  55524. return false;
  55525. if (sphereCenter.z - sphereRadius > boxMax.z)
  55526. return false;
  55527. return true;
  55528. };
  55529. var getLowestRoot = (function () {
  55530. var result = { root: 0, found: false };
  55531. return function (a, b, c, maxR) {
  55532. result.root = 0;
  55533. result.found = false;
  55534. var determinant = b * b - 4.0 * a * c;
  55535. if (determinant < 0)
  55536. return result;
  55537. var sqrtD = Math.sqrt(determinant);
  55538. var r1 = (-b - sqrtD) / (2.0 * a);
  55539. var r2 = (-b + sqrtD) / (2.0 * a);
  55540. if (r1 > r2) {
  55541. var temp = r2;
  55542. r2 = r1;
  55543. r1 = temp;
  55544. }
  55545. if (r1 > 0 && r1 < maxR) {
  55546. result.root = r1;
  55547. result.found = true;
  55548. return result;
  55549. }
  55550. if (r2 > 0 && r2 < maxR) {
  55551. result.root = r2;
  55552. result.found = true;
  55553. return result;
  55554. }
  55555. return result;
  55556. };
  55557. })();
  55558. var Collider = /** @class */ (function () {
  55559. function Collider() {
  55560. this._collisionPoint = BABYLON.Vector3.Zero();
  55561. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55562. this._tempVector = BABYLON.Vector3.Zero();
  55563. this._tempVector2 = BABYLON.Vector3.Zero();
  55564. this._tempVector3 = BABYLON.Vector3.Zero();
  55565. this._tempVector4 = BABYLON.Vector3.Zero();
  55566. this._edge = BABYLON.Vector3.Zero();
  55567. this._baseToVertex = BABYLON.Vector3.Zero();
  55568. this._destinationPoint = BABYLON.Vector3.Zero();
  55569. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55570. this._displacementVector = BABYLON.Vector3.Zero();
  55571. this._radius = BABYLON.Vector3.One();
  55572. this._retry = 0;
  55573. this._basePointWorld = BABYLON.Vector3.Zero();
  55574. this._velocityWorld = BABYLON.Vector3.Zero();
  55575. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55576. this._collisionMask = -1;
  55577. }
  55578. Object.defineProperty(Collider.prototype, "collisionMask", {
  55579. get: function () {
  55580. return this._collisionMask;
  55581. },
  55582. set: function (mask) {
  55583. this._collisionMask = !isNaN(mask) ? mask : -1;
  55584. },
  55585. enumerable: true,
  55586. configurable: true
  55587. });
  55588. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55589. /**
  55590. * Gets the plane normal used to compute the sliding response (in local space)
  55591. */
  55592. get: function () {
  55593. return this._slidePlaneNormal;
  55594. },
  55595. enumerable: true,
  55596. configurable: true
  55597. });
  55598. // Methods
  55599. Collider.prototype._initialize = function (source, dir, e) {
  55600. this._velocity = dir;
  55601. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55602. this._basePoint = source;
  55603. source.multiplyToRef(this._radius, this._basePointWorld);
  55604. dir.multiplyToRef(this._radius, this._velocityWorld);
  55605. this._velocityWorldLength = this._velocityWorld.length();
  55606. this._epsilon = e;
  55607. this.collisionFound = false;
  55608. };
  55609. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55610. pa.subtractToRef(point, this._tempVector);
  55611. pb.subtractToRef(point, this._tempVector2);
  55612. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55613. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55614. if (d < 0)
  55615. return false;
  55616. pc.subtractToRef(point, this._tempVector3);
  55617. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55618. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55619. if (d < 0)
  55620. return false;
  55621. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55622. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55623. return d >= 0;
  55624. };
  55625. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55626. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55627. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55628. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55629. return false;
  55630. }
  55631. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55632. return false;
  55633. return true;
  55634. };
  55635. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55636. var t0;
  55637. var embeddedInPlane = false;
  55638. //defensive programming, actually not needed.
  55639. if (!trianglePlaneArray) {
  55640. trianglePlaneArray = [];
  55641. }
  55642. if (!trianglePlaneArray[faceIndex]) {
  55643. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55644. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55645. }
  55646. var trianglePlane = trianglePlaneArray[faceIndex];
  55647. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55648. return;
  55649. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55650. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55651. if (normalDotVelocity == 0) {
  55652. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55653. return;
  55654. embeddedInPlane = true;
  55655. t0 = 0;
  55656. }
  55657. else {
  55658. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55659. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55660. if (t0 > t1) {
  55661. var temp = t1;
  55662. t1 = t0;
  55663. t0 = temp;
  55664. }
  55665. if (t0 > 1.0 || t1 < 0.0)
  55666. return;
  55667. if (t0 < 0)
  55668. t0 = 0;
  55669. if (t0 > 1.0)
  55670. t0 = 1.0;
  55671. }
  55672. this._collisionPoint.copyFromFloats(0, 0, 0);
  55673. var found = false;
  55674. var t = 1.0;
  55675. if (!embeddedInPlane) {
  55676. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55677. this._velocity.scaleToRef(t0, this._tempVector);
  55678. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55679. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55680. found = true;
  55681. t = t0;
  55682. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55683. }
  55684. }
  55685. if (!found) {
  55686. var velocitySquaredLength = this._velocity.lengthSquared();
  55687. var a = velocitySquaredLength;
  55688. this._basePoint.subtractToRef(p1, this._tempVector);
  55689. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55690. var c = this._tempVector.lengthSquared() - 1.0;
  55691. var lowestRoot = getLowestRoot(a, b, c, t);
  55692. if (lowestRoot.found) {
  55693. t = lowestRoot.root;
  55694. found = true;
  55695. this._collisionPoint.copyFrom(p1);
  55696. }
  55697. this._basePoint.subtractToRef(p2, this._tempVector);
  55698. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55699. c = this._tempVector.lengthSquared() - 1.0;
  55700. lowestRoot = getLowestRoot(a, b, c, t);
  55701. if (lowestRoot.found) {
  55702. t = lowestRoot.root;
  55703. found = true;
  55704. this._collisionPoint.copyFrom(p2);
  55705. }
  55706. this._basePoint.subtractToRef(p3, this._tempVector);
  55707. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55708. c = this._tempVector.lengthSquared() - 1.0;
  55709. lowestRoot = getLowestRoot(a, b, c, t);
  55710. if (lowestRoot.found) {
  55711. t = lowestRoot.root;
  55712. found = true;
  55713. this._collisionPoint.copyFrom(p3);
  55714. }
  55715. p2.subtractToRef(p1, this._edge);
  55716. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55717. var edgeSquaredLength = this._edge.lengthSquared();
  55718. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55719. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55720. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55721. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55722. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55723. lowestRoot = getLowestRoot(a, b, c, t);
  55724. if (lowestRoot.found) {
  55725. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55726. if (f >= 0.0 && f <= 1.0) {
  55727. t = lowestRoot.root;
  55728. found = true;
  55729. this._edge.scaleInPlace(f);
  55730. p1.addToRef(this._edge, this._collisionPoint);
  55731. }
  55732. }
  55733. p3.subtractToRef(p2, this._edge);
  55734. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55735. edgeSquaredLength = this._edge.lengthSquared();
  55736. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55737. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55738. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55739. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55740. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55741. lowestRoot = getLowestRoot(a, b, c, t);
  55742. if (lowestRoot.found) {
  55743. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55744. if (f >= 0.0 && f <= 1.0) {
  55745. t = lowestRoot.root;
  55746. found = true;
  55747. this._edge.scaleInPlace(f);
  55748. p2.addToRef(this._edge, this._collisionPoint);
  55749. }
  55750. }
  55751. p1.subtractToRef(p3, this._edge);
  55752. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55753. edgeSquaredLength = this._edge.lengthSquared();
  55754. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55755. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55756. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55757. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55758. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55759. lowestRoot = getLowestRoot(a, b, c, t);
  55760. if (lowestRoot.found) {
  55761. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55762. if (f >= 0.0 && f <= 1.0) {
  55763. t = lowestRoot.root;
  55764. found = true;
  55765. this._edge.scaleInPlace(f);
  55766. p3.addToRef(this._edge, this._collisionPoint);
  55767. }
  55768. }
  55769. }
  55770. if (found) {
  55771. var distToCollision = t * this._velocity.length();
  55772. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55773. if (!this.intersectionPoint) {
  55774. this.intersectionPoint = this._collisionPoint.clone();
  55775. }
  55776. else {
  55777. this.intersectionPoint.copyFrom(this._collisionPoint);
  55778. }
  55779. this._nearestDistance = distToCollision;
  55780. this.collisionFound = true;
  55781. }
  55782. }
  55783. };
  55784. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55785. for (var i = indexStart; i < indexEnd; i += 3) {
  55786. var p1 = pts[indices[i] - decal];
  55787. var p2 = pts[indices[i + 1] - decal];
  55788. var p3 = pts[indices[i + 2] - decal];
  55789. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55790. }
  55791. };
  55792. Collider.prototype._getResponse = function (pos, vel) {
  55793. pos.addToRef(vel, this._destinationPoint);
  55794. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55795. this._basePoint.addToRef(vel, pos);
  55796. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55797. this._slidePlaneNormal.normalize();
  55798. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55799. pos.addInPlace(this._displacementVector);
  55800. this.intersectionPoint.addInPlace(this._displacementVector);
  55801. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55802. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55803. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55804. };
  55805. return Collider;
  55806. }());
  55807. BABYLON.Collider = Collider;
  55808. })(BABYLON || (BABYLON = {}));
  55809. //# sourceMappingURL=babylon.collider.js.map
  55810. var BABYLON;
  55811. (function (BABYLON) {
  55812. //WebWorker code will be inserted to this variable.
  55813. BABYLON.CollisionWorker = "";
  55814. /** Defines supported task for worker process */
  55815. var WorkerTaskType;
  55816. (function (WorkerTaskType) {
  55817. /** Initialization */
  55818. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55819. /** Update of geometry */
  55820. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55821. /** Evaluate collision */
  55822. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55823. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55824. /** Defines kind of replies returned by worker */
  55825. var WorkerReplyType;
  55826. (function (WorkerReplyType) {
  55827. /** Success */
  55828. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55829. /** Unkown error */
  55830. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55831. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55832. var CollisionCoordinatorWorker = /** @class */ (function () {
  55833. function CollisionCoordinatorWorker() {
  55834. var _this = this;
  55835. this._scaledPosition = BABYLON.Vector3.Zero();
  55836. this._scaledVelocity = BABYLON.Vector3.Zero();
  55837. this.onMeshUpdated = function (transformNode) {
  55838. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55839. };
  55840. this.onGeometryUpdated = function (geometry) {
  55841. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55842. };
  55843. this._afterRender = function () {
  55844. if (!_this._init)
  55845. return;
  55846. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55847. return;
  55848. }
  55849. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55850. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55851. if (_this._runningUpdated > 4) {
  55852. return;
  55853. }
  55854. ++_this._runningUpdated;
  55855. var payload = {
  55856. updatedMeshes: _this._addUpdateMeshesList,
  55857. updatedGeometries: _this._addUpdateGeometriesList,
  55858. removedGeometries: _this._toRemoveGeometryArray,
  55859. removedMeshes: _this._toRemoveMeshesArray
  55860. };
  55861. var message = {
  55862. payload: payload,
  55863. taskType: WorkerTaskType.UPDATE
  55864. };
  55865. var serializable = [];
  55866. for (var id in payload.updatedGeometries) {
  55867. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55868. //prepare transferables
  55869. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55870. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55871. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55872. }
  55873. }
  55874. _this._worker.postMessage(message, serializable);
  55875. _this._addUpdateMeshesList = {};
  55876. _this._addUpdateGeometriesList = {};
  55877. _this._toRemoveGeometryArray = [];
  55878. _this._toRemoveMeshesArray = [];
  55879. };
  55880. this._onMessageFromWorker = function (e) {
  55881. var returnData = e.data;
  55882. if (returnData.error != WorkerReplyType.SUCCESS) {
  55883. //TODO what errors can be returned from the worker?
  55884. BABYLON.Tools.Warn("error returned from worker!");
  55885. return;
  55886. }
  55887. switch (returnData.taskType) {
  55888. case WorkerTaskType.INIT:
  55889. _this._init = true;
  55890. //Update the worked with ALL of the scene's current state
  55891. _this._scene.meshes.forEach(function (mesh) {
  55892. _this.onMeshAdded(mesh);
  55893. });
  55894. _this._scene.getGeometries().forEach(function (geometry) {
  55895. _this.onGeometryAdded(geometry);
  55896. });
  55897. break;
  55898. case WorkerTaskType.UPDATE:
  55899. _this._runningUpdated--;
  55900. break;
  55901. case WorkerTaskType.COLLIDE:
  55902. var returnPayload = returnData.payload;
  55903. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55904. return;
  55905. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55906. if (callback) {
  55907. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55908. if (mesh) {
  55909. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55910. }
  55911. }
  55912. //cleanup
  55913. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55914. break;
  55915. }
  55916. };
  55917. this._collisionsCallbackArray = [];
  55918. this._init = false;
  55919. this._runningUpdated = 0;
  55920. this._addUpdateMeshesList = {};
  55921. this._addUpdateGeometriesList = {};
  55922. this._toRemoveGeometryArray = [];
  55923. this._toRemoveMeshesArray = [];
  55924. }
  55925. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55926. if (!this._init)
  55927. return;
  55928. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55929. return;
  55930. position.divideToRef(collider._radius, this._scaledPosition);
  55931. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55932. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55933. var payload = {
  55934. collider: {
  55935. position: this._scaledPosition.asArray(),
  55936. velocity: this._scaledVelocity.asArray(),
  55937. radius: collider._radius.asArray()
  55938. },
  55939. collisionId: collisionIndex,
  55940. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55941. maximumRetry: maximumRetry
  55942. };
  55943. var message = {
  55944. payload: payload,
  55945. taskType: WorkerTaskType.COLLIDE
  55946. };
  55947. this._worker.postMessage(message);
  55948. };
  55949. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55950. this._scene = scene;
  55951. this._scene.registerAfterRender(this._afterRender);
  55952. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55953. this._worker = new Worker(workerUrl);
  55954. this._worker.onmessage = this._onMessageFromWorker;
  55955. var message = {
  55956. payload: {},
  55957. taskType: WorkerTaskType.INIT
  55958. };
  55959. this._worker.postMessage(message);
  55960. };
  55961. CollisionCoordinatorWorker.prototype.destroy = function () {
  55962. this._scene.unregisterAfterRender(this._afterRender);
  55963. this._worker.terminate();
  55964. };
  55965. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55966. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55967. this.onMeshUpdated(mesh);
  55968. };
  55969. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55970. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55971. };
  55972. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55973. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55974. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55975. this.onGeometryUpdated(geometry);
  55976. };
  55977. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55978. this._toRemoveGeometryArray.push(geometry.id);
  55979. };
  55980. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55981. var submeshes = [];
  55982. if (mesh.subMeshes) {
  55983. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55984. var boundingInfo = sm.getBoundingInfo();
  55985. return {
  55986. position: idx,
  55987. verticesStart: sm.verticesStart,
  55988. verticesCount: sm.verticesCount,
  55989. indexStart: sm.indexStart,
  55990. indexCount: sm.indexCount,
  55991. hasMaterial: !!sm.getMaterial(),
  55992. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55993. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55994. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55995. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55996. };
  55997. });
  55998. }
  55999. var geometryId = null;
  56000. if (mesh instanceof BABYLON.Mesh) {
  56001. var geometry = mesh.geometry;
  56002. geometryId = geometry ? geometry.id : null;
  56003. }
  56004. else if (mesh instanceof BABYLON.InstancedMesh) {
  56005. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56006. geometryId = geometry ? geometry.id : null;
  56007. }
  56008. var boundingInfo = mesh.getBoundingInfo();
  56009. return {
  56010. uniqueId: mesh.uniqueId,
  56011. id: mesh.id,
  56012. name: mesh.name,
  56013. geometryId: geometryId,
  56014. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56015. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56016. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56017. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56018. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56019. subMeshes: submeshes,
  56020. checkCollisions: mesh.checkCollisions
  56021. };
  56022. };
  56023. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56024. return {
  56025. id: geometry.id,
  56026. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56027. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56028. indices: new Uint32Array(geometry.getIndices() || []),
  56029. };
  56030. };
  56031. return CollisionCoordinatorWorker;
  56032. }());
  56033. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56034. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56035. function CollisionCoordinatorLegacy() {
  56036. this._scaledPosition = BABYLON.Vector3.Zero();
  56037. this._scaledVelocity = BABYLON.Vector3.Zero();
  56038. this._finalPosition = BABYLON.Vector3.Zero();
  56039. }
  56040. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56041. position.divideToRef(collider._radius, this._scaledPosition);
  56042. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56043. collider.collidedMesh = null;
  56044. collider._retry = 0;
  56045. collider._initialVelocity = this._scaledVelocity;
  56046. collider._initialPosition = this._scaledPosition;
  56047. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56048. this._finalPosition.multiplyInPlace(collider._radius);
  56049. //run the callback
  56050. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56051. };
  56052. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56053. this._scene = scene;
  56054. };
  56055. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56056. //Legacy need no destruction method.
  56057. };
  56058. //No update in legacy mode
  56059. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56060. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56061. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56062. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56063. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56064. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56065. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56066. if (excludedMesh === void 0) { excludedMesh = null; }
  56067. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56068. if (collider._retry >= maximumRetry) {
  56069. finalPosition.copyFrom(position);
  56070. return;
  56071. }
  56072. // Check if this is a mesh else camera or -1
  56073. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56074. collider._initialize(position, velocity, closeDistance);
  56075. // Check all meshes
  56076. for (var index = 0; index < this._scene.meshes.length; index++) {
  56077. var mesh = this._scene.meshes[index];
  56078. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56079. mesh._checkCollision(collider);
  56080. }
  56081. }
  56082. if (!collider.collisionFound) {
  56083. position.addToRef(velocity, finalPosition);
  56084. return;
  56085. }
  56086. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56087. collider._getResponse(position, velocity);
  56088. }
  56089. if (velocity.length() <= closeDistance) {
  56090. finalPosition.copyFrom(position);
  56091. return;
  56092. }
  56093. collider._retry++;
  56094. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56095. };
  56096. return CollisionCoordinatorLegacy;
  56097. }());
  56098. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56099. })(BABYLON || (BABYLON = {}));
  56100. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56101. var BABYLON;
  56102. (function (BABYLON) {
  56103. /**
  56104. * A particle represents one of the element emitted by a particle system.
  56105. * This is mainly define by its coordinates, direction, velocity and age.
  56106. */
  56107. var Particle = /** @class */ (function () {
  56108. /**
  56109. * Creates a new instance Particle
  56110. * @param particleSystem the particle system the particle belongs to
  56111. */
  56112. function Particle(
  56113. /**
  56114. * particleSystem the particle system the particle belongs to.
  56115. */
  56116. particleSystem) {
  56117. this.particleSystem = particleSystem;
  56118. /**
  56119. * The world position of the particle in the scene.
  56120. */
  56121. this.position = BABYLON.Vector3.Zero();
  56122. /**
  56123. * The world direction of the particle in the scene.
  56124. */
  56125. this.direction = BABYLON.Vector3.Zero();
  56126. /**
  56127. * The color of the particle.
  56128. */
  56129. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56130. /**
  56131. * The color change of the particle per step.
  56132. */
  56133. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56134. /**
  56135. * Defines how long will the life of the particle be.
  56136. */
  56137. this.lifeTime = 1.0;
  56138. /**
  56139. * The current age of the particle.
  56140. */
  56141. this.age = 0;
  56142. /**
  56143. * The current size of the particle.
  56144. */
  56145. this.size = 0;
  56146. /**
  56147. * The current angle of the particle.
  56148. */
  56149. this.angle = 0;
  56150. /**
  56151. * Defines how fast is the angle changing.
  56152. */
  56153. this.angularSpeed = 0;
  56154. /**
  56155. * Defines the cell index used by the particle to be rendered from a sprite.
  56156. */
  56157. this.cellIndex = 0;
  56158. this._currentFrameCounter = 0;
  56159. if (!this.particleSystem.isAnimationSheetEnabled) {
  56160. return;
  56161. }
  56162. this.updateCellInfoFromSystem();
  56163. }
  56164. Particle.prototype.updateCellInfoFromSystem = function () {
  56165. this.cellIndex = this.particleSystem.startSpriteCellID;
  56166. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56167. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56168. }
  56169. else {
  56170. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56171. }
  56172. };
  56173. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56174. // (ageOffset / scaledUpdateSpeed) / available cells
  56175. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56176. this._currentFrameCounter += scaledUpdateSpeed;
  56177. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56178. this._currentFrameCounter = 0;
  56179. this.cellIndex++;
  56180. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56181. this.cellIndex = this.particleSystem.endSpriteCellID;
  56182. }
  56183. }
  56184. };
  56185. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56186. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56187. this.cellIndex++;
  56188. this._currentFrameCounter = 0;
  56189. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56190. if (this.particleSystem.spriteCellLoop) {
  56191. this.cellIndex = this.particleSystem.startSpriteCellID;
  56192. }
  56193. else {
  56194. this.cellIndex = this.particleSystem.endSpriteCellID;
  56195. }
  56196. }
  56197. }
  56198. else {
  56199. this._currentFrameCounter++;
  56200. }
  56201. };
  56202. /**
  56203. * Copy the properties of particle to another one.
  56204. * @param other the particle to copy the information to.
  56205. */
  56206. Particle.prototype.copyTo = function (other) {
  56207. other.position.copyFrom(this.position);
  56208. other.direction.copyFrom(this.direction);
  56209. other.color.copyFrom(this.color);
  56210. other.colorStep.copyFrom(this.colorStep);
  56211. other.lifeTime = this.lifeTime;
  56212. other.age = this.age;
  56213. other.size = this.size;
  56214. other.angle = this.angle;
  56215. other.angularSpeed = this.angularSpeed;
  56216. other.particleSystem = this.particleSystem;
  56217. other.cellIndex = this.cellIndex;
  56218. };
  56219. return Particle;
  56220. }());
  56221. BABYLON.Particle = Particle;
  56222. })(BABYLON || (BABYLON = {}));
  56223. //# sourceMappingURL=babylon.particle.js.map
  56224. var BABYLON;
  56225. (function (BABYLON) {
  56226. /**
  56227. * This represents a particle system in Babylon.
  56228. * 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.
  56229. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56230. * @example https://doc.babylonjs.com/babylon101/particles
  56231. */
  56232. var ParticleSystem = /** @class */ (function () {
  56233. /**
  56234. * Instantiates a particle system.
  56235. * 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.
  56236. * @param name The name of the particle system
  56237. * @param capacity The max number of particles alive at the same time
  56238. * @param scene The scene the particle system belongs to
  56239. * @param customEffect a custom effect used to change the way particles are rendered by default
  56240. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56241. * @param epsilon Offset used to render the particles
  56242. */
  56243. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56244. if (customEffect === void 0) { customEffect = null; }
  56245. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56246. if (epsilon === void 0) { epsilon = 0.01; }
  56247. var _this = this;
  56248. /**
  56249. * List of animations used by the particle system.
  56250. */
  56251. this.animations = [];
  56252. /**
  56253. * The rendering group used by the Particle system to chose when to render.
  56254. */
  56255. this.renderingGroupId = 0;
  56256. /**
  56257. * The emitter represents the Mesh or position we are attaching the particle system to.
  56258. */
  56259. this.emitter = null;
  56260. /**
  56261. * The maximum number of particles to emit per frame
  56262. */
  56263. this.emitRate = 10;
  56264. /**
  56265. * If you want to launch only a few particles at once, that can be done, as well.
  56266. */
  56267. this.manualEmitCount = -1;
  56268. /**
  56269. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56270. */
  56271. this.updateSpeed = 0.01;
  56272. /**
  56273. * The amount of time the particle system is running (depends of the overall update speed).
  56274. */
  56275. this.targetStopDuration = 0;
  56276. /**
  56277. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56278. */
  56279. this.disposeOnStop = false;
  56280. /**
  56281. * Minimum power of emitting particles.
  56282. */
  56283. this.minEmitPower = 1;
  56284. /**
  56285. * Maximum power of emitting particles.
  56286. */
  56287. this.maxEmitPower = 1;
  56288. /**
  56289. * Minimum life time of emitting particles.
  56290. */
  56291. this.minLifeTime = 1;
  56292. /**
  56293. * Maximum life time of emitting particles.
  56294. */
  56295. this.maxLifeTime = 1;
  56296. /**
  56297. * Minimum Size of emitting particles.
  56298. */
  56299. this.minSize = 1;
  56300. /**
  56301. * Maximum Size of emitting particles.
  56302. */
  56303. this.maxSize = 1;
  56304. /**
  56305. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56306. */
  56307. this.minAngularSpeed = 0;
  56308. /**
  56309. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56310. */
  56311. this.maxAngularSpeed = 0;
  56312. /**
  56313. * The layer mask we are rendering the particles through.
  56314. */
  56315. this.layerMask = 0x0FFFFFFF;
  56316. /**
  56317. * This can help using your own shader to render the particle system.
  56318. * The according effect will be created
  56319. */
  56320. this.customShader = null;
  56321. /**
  56322. * By default particle system starts as soon as they are created. This prevents the
  56323. * automatic start to happen and let you decide when to start emitting particles.
  56324. */
  56325. this.preventAutoStart = false;
  56326. /**
  56327. * Callback triggered when the particle animation is ending.
  56328. */
  56329. this.onAnimationEnd = null;
  56330. /**
  56331. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56332. */
  56333. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56334. /**
  56335. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56336. * to override the particles.
  56337. */
  56338. this.forceDepthWrite = false;
  56339. /**
  56340. * You can use gravity if you want to give an orientation to your particles.
  56341. */
  56342. this.gravity = BABYLON.Vector3.Zero();
  56343. /**
  56344. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56345. */
  56346. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56347. /**
  56348. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56349. */
  56350. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56351. /**
  56352. * Color the particle will have at the end of its lifetime.
  56353. */
  56354. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56355. /**
  56356. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56357. */
  56358. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56359. /**
  56360. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56361. */
  56362. this.spriteCellLoop = true;
  56363. /**
  56364. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56365. */
  56366. this.spriteCellChangeSpeed = 0;
  56367. /**
  56368. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56369. */
  56370. this.startSpriteCellID = 0;
  56371. /**
  56372. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56373. */
  56374. this.endSpriteCellID = 0;
  56375. /**
  56376. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56377. */
  56378. this.spriteCellWidth = 0;
  56379. /**
  56380. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56381. */
  56382. this.spriteCellHeight = 0;
  56383. /**
  56384. * An event triggered when the system is disposed.
  56385. */
  56386. this.onDisposeObservable = new BABYLON.Observable();
  56387. this._particles = new Array();
  56388. this._stockParticles = new Array();
  56389. this._newPartsExcess = 0;
  56390. this._vertexBuffers = {};
  56391. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56392. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56393. this._scaledDirection = BABYLON.Vector3.Zero();
  56394. this._scaledGravity = BABYLON.Vector3.Zero();
  56395. this._currentRenderId = -1;
  56396. this._started = false;
  56397. this._stopped = false;
  56398. this._actualFrame = 0;
  56399. this._vertexBufferSize = 11;
  56400. // start of sub system methods
  56401. /**
  56402. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56403. * Its lifetime will start back at 0.
  56404. */
  56405. this.recycleParticle = function (particle) {
  56406. var lastParticle = _this._particles.pop();
  56407. if (lastParticle !== particle) {
  56408. lastParticle.copyTo(particle);
  56409. }
  56410. _this._stockParticles.push(lastParticle);
  56411. };
  56412. this._createParticle = function () {
  56413. var particle;
  56414. if (_this._stockParticles.length !== 0) {
  56415. particle = _this._stockParticles.pop();
  56416. particle.age = 0;
  56417. particle.cellIndex = _this.startSpriteCellID;
  56418. }
  56419. else {
  56420. particle = new BABYLON.Particle(_this);
  56421. }
  56422. return particle;
  56423. };
  56424. this._emitFromParticle = function (particle) {
  56425. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56426. return;
  56427. }
  56428. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56429. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56430. subSystem._rootParticleSystem = _this;
  56431. _this.activeSubSystems.push(subSystem);
  56432. subSystem.start();
  56433. };
  56434. this._appendParticleVertexes = null;
  56435. this.id = name;
  56436. this.name = name;
  56437. this._capacity = capacity;
  56438. this._epsilon = epsilon;
  56439. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56440. if (isAnimationSheetEnabled) {
  56441. this._vertexBufferSize = 12;
  56442. }
  56443. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56444. this._customEffect = customEffect;
  56445. scene.particleSystems.push(this);
  56446. this._createIndexBuffer();
  56447. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56448. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56449. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56450. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56451. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56452. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56453. if (this._isAnimationSheetEnabled) {
  56454. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56455. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56456. }
  56457. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56458. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56459. this._vertexBuffers["options"] = options;
  56460. // Default emitter type
  56461. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56462. this.updateFunction = function (particles) {
  56463. for (var index = 0; index < particles.length; index++) {
  56464. var particle = particles[index];
  56465. particle.age += _this._scaledUpdateSpeed;
  56466. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56467. _this._emitFromParticle(particle);
  56468. _this.recycleParticle(particle);
  56469. index--;
  56470. continue;
  56471. }
  56472. else {
  56473. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56474. particle.color.addInPlace(_this._scaledColorStep);
  56475. if (particle.color.a < 0)
  56476. particle.color.a = 0;
  56477. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56478. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56479. particle.position.addInPlace(_this._scaledDirection);
  56480. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56481. particle.direction.addInPlace(_this._scaledGravity);
  56482. if (_this._isAnimationSheetEnabled) {
  56483. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56484. }
  56485. }
  56486. }
  56487. };
  56488. }
  56489. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56490. /**
  56491. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56492. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56493. */
  56494. get: function () {
  56495. if (this.particleEmitterType.direction1) {
  56496. return this.particleEmitterType.direction1;
  56497. }
  56498. return BABYLON.Vector3.Zero();
  56499. },
  56500. set: function (value) {
  56501. if (this.particleEmitterType.direction1) {
  56502. this.particleEmitterType.direction1 = value;
  56503. }
  56504. },
  56505. enumerable: true,
  56506. configurable: true
  56507. });
  56508. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56509. /**
  56510. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56511. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56512. */
  56513. get: function () {
  56514. if (this.particleEmitterType.direction2) {
  56515. return this.particleEmitterType.direction2;
  56516. }
  56517. return BABYLON.Vector3.Zero();
  56518. },
  56519. set: function (value) {
  56520. if (this.particleEmitterType.direction2) {
  56521. this.particleEmitterType.direction2 = value;
  56522. }
  56523. },
  56524. enumerable: true,
  56525. configurable: true
  56526. });
  56527. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56528. /**
  56529. * 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.
  56530. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56531. */
  56532. get: function () {
  56533. if (this.particleEmitterType.minEmitBox) {
  56534. return this.particleEmitterType.minEmitBox;
  56535. }
  56536. return BABYLON.Vector3.Zero();
  56537. },
  56538. set: function (value) {
  56539. if (this.particleEmitterType.minEmitBox) {
  56540. this.particleEmitterType.minEmitBox = value;
  56541. }
  56542. },
  56543. enumerable: true,
  56544. configurable: true
  56545. });
  56546. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56547. /**
  56548. * 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.
  56549. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56550. */
  56551. get: function () {
  56552. if (this.particleEmitterType.maxEmitBox) {
  56553. return this.particleEmitterType.maxEmitBox;
  56554. }
  56555. return BABYLON.Vector3.Zero();
  56556. },
  56557. set: function (value) {
  56558. if (this.particleEmitterType.maxEmitBox) {
  56559. this.particleEmitterType.maxEmitBox = value;
  56560. }
  56561. },
  56562. enumerable: true,
  56563. configurable: true
  56564. });
  56565. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56566. /**
  56567. * Sets a callback that will be triggered when the system is disposed.
  56568. */
  56569. set: function (callback) {
  56570. if (this._onDisposeObserver) {
  56571. this.onDisposeObservable.remove(this._onDisposeObserver);
  56572. }
  56573. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56574. },
  56575. enumerable: true,
  56576. configurable: true
  56577. });
  56578. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56579. /**
  56580. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56581. */
  56582. get: function () {
  56583. return this._isAnimationSheetEnabled;
  56584. },
  56585. enumerable: true,
  56586. configurable: true
  56587. });
  56588. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56589. //end of Sub-emitter
  56590. /**
  56591. * Gets the current list of active particles
  56592. */
  56593. get: function () {
  56594. return this._particles;
  56595. },
  56596. enumerable: true,
  56597. configurable: true
  56598. });
  56599. /**
  56600. * Returns the string "ParticleSystem"
  56601. * @returns a string containing the class name
  56602. */
  56603. ParticleSystem.prototype.getClassName = function () {
  56604. return "ParticleSystem";
  56605. };
  56606. ParticleSystem.prototype._createIndexBuffer = function () {
  56607. var indices = [];
  56608. var index = 0;
  56609. for (var count = 0; count < this._capacity; count++) {
  56610. indices.push(index);
  56611. indices.push(index + 1);
  56612. indices.push(index + 2);
  56613. indices.push(index);
  56614. indices.push(index + 2);
  56615. indices.push(index + 3);
  56616. index += 4;
  56617. }
  56618. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56619. };
  56620. /**
  56621. * Gets the maximum number of particles active at the same time.
  56622. * @returns The max number of active particles.
  56623. */
  56624. ParticleSystem.prototype.getCapacity = function () {
  56625. return this._capacity;
  56626. };
  56627. /**
  56628. * Gets Wether there are still active particles in the system.
  56629. * @returns True if it is alive, otherwise false.
  56630. */
  56631. ParticleSystem.prototype.isAlive = function () {
  56632. return this._alive;
  56633. };
  56634. /**
  56635. * Gets Wether the system has been started.
  56636. * @returns True if it has been started, otherwise false.
  56637. */
  56638. ParticleSystem.prototype.isStarted = function () {
  56639. return this._started;
  56640. };
  56641. /**
  56642. * Starts the particle system and begins to emit.
  56643. */
  56644. ParticleSystem.prototype.start = function () {
  56645. this._started = true;
  56646. this._stopped = false;
  56647. this._actualFrame = 0;
  56648. if (this.subEmitters && this.subEmitters.length != 0) {
  56649. this.activeSubSystems = new Array();
  56650. }
  56651. };
  56652. /**
  56653. * Stops the particle system.
  56654. * @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.
  56655. */
  56656. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56657. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56658. this._stopped = true;
  56659. if (stopSubEmitters) {
  56660. this._stopSubEmitters();
  56661. }
  56662. };
  56663. // animation sheet
  56664. /**
  56665. * Remove all active particles
  56666. */
  56667. ParticleSystem.prototype.reset = function () {
  56668. this._stockParticles = [];
  56669. this._particles = [];
  56670. };
  56671. /**
  56672. * @hidden (for internal use only)
  56673. */
  56674. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56675. var offset = index * this._vertexBufferSize;
  56676. this._vertexData[offset] = particle.position.x;
  56677. this._vertexData[offset + 1] = particle.position.y;
  56678. this._vertexData[offset + 2] = particle.position.z;
  56679. this._vertexData[offset + 3] = particle.color.r;
  56680. this._vertexData[offset + 4] = particle.color.g;
  56681. this._vertexData[offset + 5] = particle.color.b;
  56682. this._vertexData[offset + 6] = particle.color.a;
  56683. this._vertexData[offset + 7] = particle.angle;
  56684. this._vertexData[offset + 8] = particle.size;
  56685. this._vertexData[offset + 9] = offsetX;
  56686. this._vertexData[offset + 10] = offsetY;
  56687. };
  56688. /**
  56689. * @hidden (for internal use only)
  56690. */
  56691. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56692. if (offsetX === 0)
  56693. offsetX = this._epsilon;
  56694. else if (offsetX === 1)
  56695. offsetX = 1 - this._epsilon;
  56696. if (offsetY === 0)
  56697. offsetY = this._epsilon;
  56698. else if (offsetY === 1)
  56699. offsetY = 1 - this._epsilon;
  56700. var offset = index * this._vertexBufferSize;
  56701. this._vertexData[offset] = particle.position.x;
  56702. this._vertexData[offset + 1] = particle.position.y;
  56703. this._vertexData[offset + 2] = particle.position.z;
  56704. this._vertexData[offset + 3] = particle.color.r;
  56705. this._vertexData[offset + 4] = particle.color.g;
  56706. this._vertexData[offset + 5] = particle.color.b;
  56707. this._vertexData[offset + 6] = particle.color.a;
  56708. this._vertexData[offset + 7] = particle.angle;
  56709. this._vertexData[offset + 8] = particle.size;
  56710. this._vertexData[offset + 9] = offsetX;
  56711. this._vertexData[offset + 10] = offsetY;
  56712. this._vertexData[offset + 11] = particle.cellIndex;
  56713. };
  56714. ParticleSystem.prototype._stopSubEmitters = function () {
  56715. if (!this.activeSubSystems) {
  56716. return;
  56717. }
  56718. this.activeSubSystems.forEach(function (subSystem) {
  56719. subSystem.stop(true);
  56720. });
  56721. this.activeSubSystems = new Array();
  56722. };
  56723. ParticleSystem.prototype._removeFromRoot = function () {
  56724. if (!this._rootParticleSystem) {
  56725. return;
  56726. }
  56727. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56728. if (index !== -1) {
  56729. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56730. }
  56731. };
  56732. // end of sub system methods
  56733. ParticleSystem.prototype._update = function (newParticles) {
  56734. // Update current
  56735. this._alive = this._particles.length > 0;
  56736. this.updateFunction(this._particles);
  56737. // Add new ones
  56738. var worldMatrix;
  56739. if (this.emitter.position) {
  56740. var emitterMesh = this.emitter;
  56741. worldMatrix = emitterMesh.getWorldMatrix();
  56742. }
  56743. else {
  56744. var emitterPosition = this.emitter;
  56745. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56746. }
  56747. var particle;
  56748. for (var index = 0; index < newParticles; index++) {
  56749. if (this._particles.length === this._capacity) {
  56750. break;
  56751. }
  56752. particle = this._createParticle();
  56753. this._particles.push(particle);
  56754. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56755. if (this.startPositionFunction) {
  56756. this.startPositionFunction(worldMatrix, particle.position, particle);
  56757. }
  56758. else {
  56759. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56760. }
  56761. if (this.startDirectionFunction) {
  56762. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56763. }
  56764. else {
  56765. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56766. }
  56767. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56768. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56769. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56770. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56771. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56772. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56773. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56774. }
  56775. };
  56776. ParticleSystem.prototype._getEffect = function () {
  56777. if (this._customEffect) {
  56778. return this._customEffect;
  56779. }
  56780. ;
  56781. var defines = [];
  56782. if (this._scene.clipPlane) {
  56783. defines.push("#define CLIPPLANE");
  56784. }
  56785. if (this._isAnimationSheetEnabled) {
  56786. defines.push("#define ANIMATESHEET");
  56787. }
  56788. // Effect
  56789. var join = defines.join("\n");
  56790. if (this._cachedDefines !== join) {
  56791. this._cachedDefines = join;
  56792. var attributesNamesOrOptions;
  56793. var effectCreationOption;
  56794. if (this._isAnimationSheetEnabled) {
  56795. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56796. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56797. }
  56798. else {
  56799. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56800. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56801. }
  56802. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56803. }
  56804. return this._effect;
  56805. };
  56806. /**
  56807. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56808. */
  56809. ParticleSystem.prototype.animate = function () {
  56810. if (!this._started)
  56811. return;
  56812. var effect = this._getEffect();
  56813. // Check
  56814. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56815. return;
  56816. if (this._currentRenderId === this._scene.getRenderId()) {
  56817. return;
  56818. }
  56819. this._currentRenderId = this._scene.getRenderId();
  56820. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56821. // determine the number of particles we need to create
  56822. var newParticles;
  56823. if (this.manualEmitCount > -1) {
  56824. newParticles = this.manualEmitCount;
  56825. this._newPartsExcess = 0;
  56826. this.manualEmitCount = 0;
  56827. }
  56828. else {
  56829. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56830. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56831. }
  56832. if (this._newPartsExcess > 1.0) {
  56833. newParticles += this._newPartsExcess >> 0;
  56834. this._newPartsExcess -= this._newPartsExcess >> 0;
  56835. }
  56836. this._alive = false;
  56837. if (!this._stopped) {
  56838. this._actualFrame += this._scaledUpdateSpeed;
  56839. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56840. this.stop();
  56841. }
  56842. else {
  56843. newParticles = 0;
  56844. }
  56845. this._update(newParticles);
  56846. // Stopped?
  56847. if (this._stopped) {
  56848. if (!this._alive) {
  56849. this._started = false;
  56850. if (this.onAnimationEnd) {
  56851. this.onAnimationEnd();
  56852. }
  56853. if (this.disposeOnStop) {
  56854. this._scene._toBeDisposed.push(this);
  56855. }
  56856. }
  56857. }
  56858. // Animation sheet
  56859. if (this._isAnimationSheetEnabled) {
  56860. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56861. }
  56862. else {
  56863. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56864. }
  56865. // Update VBO
  56866. var offset = 0;
  56867. for (var index = 0; index < this._particles.length; index++) {
  56868. var particle = this._particles[index];
  56869. this._appendParticleVertexes(offset, particle);
  56870. offset += 4;
  56871. }
  56872. if (this._vertexBuffer) {
  56873. this._vertexBuffer.update(this._vertexData);
  56874. }
  56875. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56876. this.stop();
  56877. }
  56878. };
  56879. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56880. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56881. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56882. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56883. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56884. };
  56885. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56886. this._appendParticleVertex(offset++, particle, 0, 0);
  56887. this._appendParticleVertex(offset++, particle, 1, 0);
  56888. this._appendParticleVertex(offset++, particle, 1, 1);
  56889. this._appendParticleVertex(offset++, particle, 0, 1);
  56890. };
  56891. /**
  56892. * Rebuilds the particle system.
  56893. */
  56894. ParticleSystem.prototype.rebuild = function () {
  56895. this._createIndexBuffer();
  56896. if (this._vertexBuffer) {
  56897. this._vertexBuffer._rebuild();
  56898. }
  56899. };
  56900. /**
  56901. * Is this system ready to be used/rendered
  56902. * @return true if the system is ready
  56903. */
  56904. ParticleSystem.prototype.isReady = function () {
  56905. var effect = this._getEffect();
  56906. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56907. return false;
  56908. }
  56909. return true;
  56910. };
  56911. /**
  56912. * Renders the particle system in its current state.
  56913. * @returns the current number of particles
  56914. */
  56915. ParticleSystem.prototype.render = function () {
  56916. var effect = this._getEffect();
  56917. // Check
  56918. if (!this.isReady() || !this._particles.length) {
  56919. return 0;
  56920. }
  56921. var engine = this._scene.getEngine();
  56922. // Render
  56923. engine.enableEffect(effect);
  56924. engine.setState(false);
  56925. var viewMatrix = this._scene.getViewMatrix();
  56926. effect.setTexture("diffuseSampler", this.particleTexture);
  56927. effect.setMatrix("view", viewMatrix);
  56928. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56929. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56930. var baseSize = this.particleTexture.getBaseSize();
  56931. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56932. }
  56933. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56934. if (this._scene.clipPlane) {
  56935. var clipPlane = this._scene.clipPlane;
  56936. var invView = viewMatrix.clone();
  56937. invView.invert();
  56938. effect.setMatrix("invView", invView);
  56939. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56940. }
  56941. // VBOs
  56942. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56943. // Draw order
  56944. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56945. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56946. }
  56947. else {
  56948. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56949. }
  56950. if (this.forceDepthWrite) {
  56951. engine.setDepthWrite(true);
  56952. }
  56953. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56954. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56955. return this._particles.length;
  56956. };
  56957. /**
  56958. * Disposes the particle system and free the associated resources
  56959. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56960. */
  56961. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56962. if (disposeTexture === void 0) { disposeTexture = true; }
  56963. if (this._vertexBuffer) {
  56964. this._vertexBuffer.dispose();
  56965. this._vertexBuffer = null;
  56966. }
  56967. if (this._indexBuffer) {
  56968. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56969. this._indexBuffer = null;
  56970. }
  56971. if (disposeTexture && this.particleTexture) {
  56972. this.particleTexture.dispose();
  56973. this.particleTexture = null;
  56974. }
  56975. this._removeFromRoot();
  56976. // Remove from scene
  56977. var index = this._scene.particleSystems.indexOf(this);
  56978. if (index > -1) {
  56979. this._scene.particleSystems.splice(index, 1);
  56980. }
  56981. // Callback
  56982. this.onDisposeObservable.notifyObservers(this);
  56983. this.onDisposeObservable.clear();
  56984. };
  56985. /**
  56986. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56987. * @param radius The radius of the sphere to emit from
  56988. * @returns the emitter
  56989. */
  56990. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56991. if (radius === void 0) { radius = 1; }
  56992. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56993. this.particleEmitterType = particleEmitter;
  56994. return particleEmitter;
  56995. };
  56996. /**
  56997. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56998. * @param radius The radius of the sphere to emit from
  56999. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57000. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57001. * @returns the emitter
  57002. */
  57003. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57004. if (radius === void 0) { radius = 1; }
  57005. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57006. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57007. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57008. this.particleEmitterType = particleEmitter;
  57009. return particleEmitter;
  57010. };
  57011. /**
  57012. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  57013. * @param radius The radius of the cone to emit from
  57014. * @param angle The base angle of the cone
  57015. * @returns the emitter
  57016. */
  57017. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57018. if (radius === void 0) { radius = 1; }
  57019. if (angle === void 0) { angle = Math.PI / 4; }
  57020. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57021. this.particleEmitterType = particleEmitter;
  57022. return particleEmitter;
  57023. };
  57024. // 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.
  57025. /**
  57026. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57027. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57028. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57029. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57030. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57031. * @returns the emitter
  57032. */
  57033. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57034. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57035. this.particleEmitterType = particleEmitter;
  57036. this.direction1 = direction1;
  57037. this.direction2 = direction2;
  57038. this.minEmitBox = minEmitBox;
  57039. this.maxEmitBox = maxEmitBox;
  57040. return particleEmitter;
  57041. };
  57042. // Clone
  57043. /**
  57044. * Clones the particle system.
  57045. * @param name The name of the cloned object
  57046. * @param newEmitter The new emitter to use
  57047. * @returns the cloned particle system
  57048. */
  57049. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57050. var custom = null;
  57051. var program = null;
  57052. if (this.customShader != null) {
  57053. program = this.customShader;
  57054. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57055. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57056. }
  57057. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57058. result.customShader = program;
  57059. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57060. if (newEmitter === undefined) {
  57061. newEmitter = this.emitter;
  57062. }
  57063. result.emitter = newEmitter;
  57064. if (this.particleTexture) {
  57065. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57066. }
  57067. if (!this.preventAutoStart) {
  57068. result.start();
  57069. }
  57070. return result;
  57071. };
  57072. /**
  57073. * Serializes the particle system to a JSON object.
  57074. * @returns the JSON object
  57075. */
  57076. ParticleSystem.prototype.serialize = function () {
  57077. var serializationObject = {};
  57078. serializationObject.name = this.name;
  57079. serializationObject.id = this.id;
  57080. // Emitter
  57081. if (this.emitter.position) {
  57082. var emitterMesh = this.emitter;
  57083. serializationObject.emitterId = emitterMesh.id;
  57084. }
  57085. else {
  57086. var emitterPosition = this.emitter;
  57087. serializationObject.emitter = emitterPosition.asArray();
  57088. }
  57089. serializationObject.capacity = this.getCapacity();
  57090. if (this.particleTexture) {
  57091. serializationObject.textureName = this.particleTexture.name;
  57092. }
  57093. // Animations
  57094. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57095. // Particle system
  57096. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57097. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57098. serializationObject.minSize = this.minSize;
  57099. serializationObject.maxSize = this.maxSize;
  57100. serializationObject.minEmitPower = this.minEmitPower;
  57101. serializationObject.maxEmitPower = this.maxEmitPower;
  57102. serializationObject.minLifeTime = this.minLifeTime;
  57103. serializationObject.maxLifeTime = this.maxLifeTime;
  57104. serializationObject.emitRate = this.emitRate;
  57105. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57106. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57107. serializationObject.gravity = this.gravity.asArray();
  57108. serializationObject.direction1 = this.direction1.asArray();
  57109. serializationObject.direction2 = this.direction2.asArray();
  57110. serializationObject.color1 = this.color1.asArray();
  57111. serializationObject.color2 = this.color2.asArray();
  57112. serializationObject.colorDead = this.colorDead.asArray();
  57113. serializationObject.updateSpeed = this.updateSpeed;
  57114. serializationObject.targetStopDuration = this.targetStopDuration;
  57115. serializationObject.textureMask = this.textureMask.asArray();
  57116. serializationObject.blendMode = this.blendMode;
  57117. serializationObject.customShader = this.customShader;
  57118. serializationObject.preventAutoStart = this.preventAutoStart;
  57119. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57120. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57121. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57122. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57123. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57124. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57125. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57126. // Emitter
  57127. if (this.particleEmitterType) {
  57128. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57129. }
  57130. return serializationObject;
  57131. };
  57132. /**
  57133. * Parses a JSON object to create a particle system.
  57134. * @param parsedParticleSystem The JSON object to parse
  57135. * @param scene The scene to create the particle system in
  57136. * @param rootUrl The root url to use to load external dependencies like texture
  57137. * @returns the Parsed particle system
  57138. */
  57139. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57140. var name = parsedParticleSystem.name;
  57141. var custom = null;
  57142. var program = null;
  57143. if (parsedParticleSystem.customShader) {
  57144. program = parsedParticleSystem.customShader;
  57145. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57146. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57147. }
  57148. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57149. particleSystem.customShader = program;
  57150. if (parsedParticleSystem.id) {
  57151. particleSystem.id = parsedParticleSystem.id;
  57152. }
  57153. // Auto start
  57154. if (parsedParticleSystem.preventAutoStart) {
  57155. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57156. }
  57157. // Texture
  57158. if (parsedParticleSystem.textureName) {
  57159. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57160. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57161. }
  57162. // Emitter
  57163. if (parsedParticleSystem.emitterId) {
  57164. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57165. }
  57166. else {
  57167. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57168. }
  57169. // Animations
  57170. if (parsedParticleSystem.animations) {
  57171. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57172. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57173. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57174. }
  57175. }
  57176. if (parsedParticleSystem.autoAnimate) {
  57177. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57178. }
  57179. // Particle system
  57180. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57181. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57182. particleSystem.minSize = parsedParticleSystem.minSize;
  57183. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57184. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57185. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57186. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57187. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57188. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57189. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57190. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57191. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57192. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57193. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57194. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57195. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57196. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57197. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57198. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57199. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57200. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57201. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57202. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57203. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57204. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57205. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57206. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57207. if (!particleSystem.preventAutoStart) {
  57208. particleSystem.start();
  57209. }
  57210. return particleSystem;
  57211. };
  57212. /**
  57213. * Source color is added to the destination color without alpha affecting the result.
  57214. */
  57215. ParticleSystem.BLENDMODE_ONEONE = 0;
  57216. /**
  57217. * Blend current color and particle color using particle’s alpha.
  57218. */
  57219. ParticleSystem.BLENDMODE_STANDARD = 1;
  57220. return ParticleSystem;
  57221. }());
  57222. BABYLON.ParticleSystem = ParticleSystem;
  57223. })(BABYLON || (BABYLON = {}));
  57224. //# sourceMappingURL=babylon.particleSystem.js.map
  57225. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57226. var BABYLON;
  57227. (function (BABYLON) {
  57228. /**
  57229. * Particle emitter emitting particles from the inside of a box.
  57230. * It emits the particles randomly between 2 given directions.
  57231. */
  57232. var BoxParticleEmitter = /** @class */ (function () {
  57233. /**
  57234. * Creates a new instance BoxParticleEmitter
  57235. */
  57236. function BoxParticleEmitter() {
  57237. /**
  57238. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57239. */
  57240. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57241. /**
  57242. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57243. */
  57244. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57245. /**
  57246. * 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.
  57247. */
  57248. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57249. /**
  57250. * 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.
  57251. */
  57252. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57253. }
  57254. /**
  57255. * Called by the particle System when the direction is computed for the created particle.
  57256. * @param emitPower is the power of the particle (speed)
  57257. * @param worldMatrix is the world matrix of the particle system
  57258. * @param directionToUpdate is the direction vector to update with the result
  57259. * @param particle is the particle we are computed the direction for
  57260. */
  57261. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57262. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57263. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57264. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57265. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57266. };
  57267. /**
  57268. * Called by the particle System when the position is computed for the created particle.
  57269. * @param worldMatrix is the world matrix of the particle system
  57270. * @param positionToUpdate is the position vector to update with the result
  57271. * @param particle is the particle we are computed the position for
  57272. */
  57273. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57274. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57275. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57276. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57277. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57278. };
  57279. /**
  57280. * Clones the current emitter and returns a copy of it
  57281. * @returns the new emitter
  57282. */
  57283. BoxParticleEmitter.prototype.clone = function () {
  57284. var newOne = new BoxParticleEmitter();
  57285. BABYLON.Tools.DeepCopy(this, newOne);
  57286. return newOne;
  57287. };
  57288. /**
  57289. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57290. * @param effect defines the update shader
  57291. */
  57292. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57293. effect.setVector3("direction1", this.direction1);
  57294. effect.setVector3("direction2", this.direction2);
  57295. effect.setVector3("minEmitBox", this.minEmitBox);
  57296. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57297. };
  57298. /**
  57299. * Returns a string to use to update the GPU particles update shader
  57300. * @returns a string containng the defines string
  57301. */
  57302. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57303. return "#define BOXEMITTER";
  57304. };
  57305. /**
  57306. * Returns the string "BoxEmitter"
  57307. * @returns a string containing the class name
  57308. */
  57309. BoxParticleEmitter.prototype.getClassName = function () {
  57310. return "BoxEmitter";
  57311. };
  57312. /**
  57313. * Serializes the particle system to a JSON object.
  57314. * @returns the JSON object
  57315. */
  57316. BoxParticleEmitter.prototype.serialize = function () {
  57317. var serializationObject = {};
  57318. serializationObject.type = this.getClassName();
  57319. serializationObject.direction1 = this.direction1.asArray();
  57320. serializationObject.direction2 = this.direction2.asArray();
  57321. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57322. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57323. return serializationObject;
  57324. };
  57325. /**
  57326. * Parse properties from a JSON object
  57327. * @param serializationObject defines the JSON object
  57328. */
  57329. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57330. this.direction1.copyFrom(serializationObject.direction1);
  57331. this.direction2.copyFrom(serializationObject.direction2);
  57332. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57333. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57334. };
  57335. return BoxParticleEmitter;
  57336. }());
  57337. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57338. })(BABYLON || (BABYLON = {}));
  57339. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57340. var BABYLON;
  57341. (function (BABYLON) {
  57342. /**
  57343. * Particle emitter emitting particles from the inside of a cone.
  57344. * It emits the particles alongside the cone volume from the base to the particle.
  57345. * The emission direction might be randomized.
  57346. */
  57347. var ConeParticleEmitter = /** @class */ (function () {
  57348. /**
  57349. * Creates a new instance ConeParticleEmitter
  57350. * @param radius the radius of the emission cone (1 by default)
  57351. * @param angles the cone base angle (PI by default)
  57352. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57353. */
  57354. function ConeParticleEmitter(radius,
  57355. /**
  57356. * The radius of the emission cone.
  57357. */
  57358. angle,
  57359. /**
  57360. * The cone base angle.
  57361. */
  57362. directionRandomizer) {
  57363. if (radius === void 0) { radius = 1; }
  57364. if (angle === void 0) { angle = Math.PI; }
  57365. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57366. this.angle = angle;
  57367. this.directionRandomizer = directionRandomizer;
  57368. this.radius = radius;
  57369. }
  57370. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57371. /**
  57372. * Gets the radius of the emission cone.
  57373. */
  57374. get: function () {
  57375. return this._radius;
  57376. },
  57377. /**
  57378. * Sets the radius of the emission cone.
  57379. */
  57380. set: function (value) {
  57381. this._radius = value;
  57382. if (this.angle !== 0) {
  57383. this._height = value / Math.tan(this.angle / 2);
  57384. }
  57385. else {
  57386. this._height = 1;
  57387. }
  57388. },
  57389. enumerable: true,
  57390. configurable: true
  57391. });
  57392. /**
  57393. * Called by the particle System when the direction is computed for the created particle.
  57394. * @param emitPower is the power of the particle (speed)
  57395. * @param worldMatrix is the world matrix of the particle system
  57396. * @param directionToUpdate is the direction vector to update with the result
  57397. * @param particle is the particle we are computed the direction for
  57398. */
  57399. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57400. if (this.angle === 0) {
  57401. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57402. }
  57403. else {
  57404. // measure the direction Vector from the emitter to the particle.
  57405. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57406. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57407. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57408. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57409. direction.x += randX;
  57410. direction.y += randY;
  57411. direction.z += randZ;
  57412. direction.normalize();
  57413. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57414. }
  57415. };
  57416. /**
  57417. * Called by the particle System when the position is computed for the created particle.
  57418. * @param worldMatrix is the world matrix of the particle system
  57419. * @param positionToUpdate is the position vector to update with the result
  57420. * @param particle is the particle we are computed the position for
  57421. */
  57422. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57423. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57424. var h = BABYLON.Scalar.RandomRange(0, 1);
  57425. // Better distribution in a cone at normal angles.
  57426. h = 1 - h * h;
  57427. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57428. radius = radius * h;
  57429. var randX = radius * Math.sin(s);
  57430. var randZ = radius * Math.cos(s);
  57431. var randY = h * this._height;
  57432. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57433. };
  57434. /**
  57435. * Clones the current emitter and returns a copy of it
  57436. * @returns the new emitter
  57437. */
  57438. ConeParticleEmitter.prototype.clone = function () {
  57439. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57440. BABYLON.Tools.DeepCopy(this, newOne);
  57441. return newOne;
  57442. };
  57443. /**
  57444. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57445. * @param effect defines the update shader
  57446. */
  57447. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57448. effect.setFloat("radius", this.radius);
  57449. effect.setFloat("coneAngle", this.angle);
  57450. effect.setFloat("height", this._height);
  57451. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57452. };
  57453. /**
  57454. * Returns a string to use to update the GPU particles update shader
  57455. * @returns a string containng the defines string
  57456. */
  57457. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57458. return "#define CONEEMITTER";
  57459. };
  57460. /**
  57461. * Returns the string "BoxEmitter"
  57462. * @returns a string containing the class name
  57463. */
  57464. ConeParticleEmitter.prototype.getClassName = function () {
  57465. return "ConeEmitter";
  57466. };
  57467. /**
  57468. * Serializes the particle system to a JSON object.
  57469. * @returns the JSON object
  57470. */
  57471. ConeParticleEmitter.prototype.serialize = function () {
  57472. var serializationObject = {};
  57473. serializationObject.type = this.getClassName();
  57474. serializationObject.radius = this.radius;
  57475. serializationObject.angle = this.angle;
  57476. serializationObject.directionRandomizer = this.directionRandomizer;
  57477. return serializationObject;
  57478. };
  57479. /**
  57480. * Parse properties from a JSON object
  57481. * @param serializationObject defines the JSON object
  57482. */
  57483. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57484. this.radius = serializationObject.radius;
  57485. this.angle = serializationObject.angle;
  57486. this.directionRandomizer = serializationObject.directionRandomizer;
  57487. };
  57488. return ConeParticleEmitter;
  57489. }());
  57490. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57491. })(BABYLON || (BABYLON = {}));
  57492. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57493. var BABYLON;
  57494. (function (BABYLON) {
  57495. /**
  57496. * Particle emitter emitting particles from the inside of a sphere.
  57497. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57498. */
  57499. var SphereParticleEmitter = /** @class */ (function () {
  57500. /**
  57501. * Creates a new instance SphereParticleEmitter
  57502. * @param radius the radius of the emission sphere (1 by default)
  57503. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57504. */
  57505. function SphereParticleEmitter(
  57506. /**
  57507. * The radius of the emission sphere.
  57508. */
  57509. radius,
  57510. /**
  57511. * How much to randomize the particle direction [0-1].
  57512. */
  57513. directionRandomizer) {
  57514. if (radius === void 0) { radius = 1; }
  57515. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57516. this.radius = radius;
  57517. this.directionRandomizer = directionRandomizer;
  57518. }
  57519. /**
  57520. * Called by the particle System when the direction is computed for the created particle.
  57521. * @param emitPower is the power of the particle (speed)
  57522. * @param worldMatrix is the world matrix of the particle system
  57523. * @param directionToUpdate is the direction vector to update with the result
  57524. * @param particle is the particle we are computed the direction for
  57525. */
  57526. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57527. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57528. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57529. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57530. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57531. direction.x += randX;
  57532. direction.y += randY;
  57533. direction.z += randZ;
  57534. direction.normalize();
  57535. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57536. };
  57537. /**
  57538. * Called by the particle System when the position is computed for the created particle.
  57539. * @param worldMatrix is the world matrix of the particle system
  57540. * @param positionToUpdate is the position vector to update with the result
  57541. * @param particle is the particle we are computed the position for
  57542. */
  57543. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57544. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57545. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57546. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57547. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57548. var randY = randRadius * Math.cos(theta);
  57549. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57550. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57551. };
  57552. /**
  57553. * Clones the current emitter and returns a copy of it
  57554. * @returns the new emitter
  57555. */
  57556. SphereParticleEmitter.prototype.clone = function () {
  57557. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57558. BABYLON.Tools.DeepCopy(this, newOne);
  57559. return newOne;
  57560. };
  57561. /**
  57562. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57563. * @param effect defines the update shader
  57564. */
  57565. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57566. effect.setFloat("radius", this.radius);
  57567. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57568. };
  57569. /**
  57570. * Returns a string to use to update the GPU particles update shader
  57571. * @returns a string containng the defines string
  57572. */
  57573. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57574. return "#define SPHEREEMITTER";
  57575. };
  57576. /**
  57577. * Returns the string "SphereParticleEmitter"
  57578. * @returns a string containing the class name
  57579. */
  57580. SphereParticleEmitter.prototype.getClassName = function () {
  57581. return "SphereParticleEmitter";
  57582. };
  57583. /**
  57584. * Serializes the particle system to a JSON object.
  57585. * @returns the JSON object
  57586. */
  57587. SphereParticleEmitter.prototype.serialize = function () {
  57588. var serializationObject = {};
  57589. serializationObject.type = this.getClassName();
  57590. serializationObject.radius = this.radius;
  57591. serializationObject.directionRandomizer = this.directionRandomizer;
  57592. return serializationObject;
  57593. };
  57594. /**
  57595. * Parse properties from a JSON object
  57596. * @param serializationObject defines the JSON object
  57597. */
  57598. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57599. this.radius = serializationObject.radius;
  57600. this.directionRandomizer = serializationObject.directionRandomizer;
  57601. };
  57602. return SphereParticleEmitter;
  57603. }());
  57604. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57605. /**
  57606. * Particle emitter emitting particles from the inside of a sphere.
  57607. * It emits the particles randomly between two vectors.
  57608. */
  57609. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57610. __extends(SphereDirectedParticleEmitter, _super);
  57611. /**
  57612. * Creates a new instance SphereDirectedParticleEmitter
  57613. * @param radius the radius of the emission sphere (1 by default)
  57614. * @param direction1 the min limit of the emission direction (up vector by default)
  57615. * @param direction2 the max limit of the emission direction (up vector by default)
  57616. */
  57617. function SphereDirectedParticleEmitter(radius,
  57618. /**
  57619. * The min limit of the emission direction.
  57620. */
  57621. direction1,
  57622. /**
  57623. * The max limit of the emission direction.
  57624. */
  57625. direction2) {
  57626. if (radius === void 0) { radius = 1; }
  57627. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57628. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57629. var _this = _super.call(this, radius) || this;
  57630. _this.direction1 = direction1;
  57631. _this.direction2 = direction2;
  57632. return _this;
  57633. }
  57634. /**
  57635. * Called by the particle System when the direction is computed for the created particle.
  57636. * @param emitPower is the power of the particle (speed)
  57637. * @param worldMatrix is the world matrix of the particle system
  57638. * @param directionToUpdate is the direction vector to update with the result
  57639. * @param particle is the particle we are computed the direction for
  57640. */
  57641. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57642. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57643. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57644. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57645. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57646. };
  57647. /**
  57648. * Clones the current emitter and returns a copy of it
  57649. * @returns the new emitter
  57650. */
  57651. SphereDirectedParticleEmitter.prototype.clone = function () {
  57652. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57653. BABYLON.Tools.DeepCopy(this, newOne);
  57654. return newOne;
  57655. };
  57656. /**
  57657. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57658. * @param effect defines the update shader
  57659. */
  57660. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57661. effect.setFloat("radius", this.radius);
  57662. effect.setVector3("direction1", this.direction1);
  57663. effect.setVector3("direction2", this.direction2);
  57664. };
  57665. /**
  57666. * Returns a string to use to update the GPU particles update shader
  57667. * @returns a string containng the defines string
  57668. */
  57669. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57670. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57671. };
  57672. /**
  57673. * Returns the string "SphereDirectedParticleEmitter"
  57674. * @returns a string containing the class name
  57675. */
  57676. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57677. return "SphereDirectedParticleEmitter";
  57678. };
  57679. /**
  57680. * Serializes the particle system to a JSON object.
  57681. * @returns the JSON object
  57682. */
  57683. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57684. var serializationObject = _super.prototype.serialize.call(this);
  57685. serializationObject.direction1 = this.direction1.asArray();
  57686. serializationObject.direction2 = this.direction2.asArray();
  57687. return serializationObject;
  57688. };
  57689. /**
  57690. * Parse properties from a JSON object
  57691. * @param serializationObject defines the JSON object
  57692. */
  57693. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57694. _super.prototype.parse.call(this, serializationObject);
  57695. this.direction1.copyFrom(serializationObject.direction1);
  57696. this.direction2.copyFrom(serializationObject.direction2);
  57697. };
  57698. return SphereDirectedParticleEmitter;
  57699. }(SphereParticleEmitter));
  57700. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57701. })(BABYLON || (BABYLON = {}));
  57702. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57703. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57704. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57705. s = arguments[i];
  57706. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57707. t[p] = s[p];
  57708. }
  57709. return t;
  57710. };
  57711. var BABYLON;
  57712. (function (BABYLON) {
  57713. /**
  57714. * This represents a GPU particle system in Babylon
  57715. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57716. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57717. */
  57718. var GPUParticleSystem = /** @class */ (function () {
  57719. /**
  57720. * Instantiates a GPU particle system.
  57721. * 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.
  57722. * @param name The name of the particle system
  57723. * @param capacity The max number of particles alive at the same time
  57724. * @param scene The scene the particle system belongs to
  57725. */
  57726. function GPUParticleSystem(name, options, scene) {
  57727. /**
  57728. * The emitter represents the Mesh or position we are attaching the particle system to.
  57729. */
  57730. this.emitter = null;
  57731. /**
  57732. * The rendering group used by the Particle system to chose when to render.
  57733. */
  57734. this.renderingGroupId = 0;
  57735. /**
  57736. * The layer mask we are rendering the particles through.
  57737. */
  57738. this.layerMask = 0x0FFFFFFF;
  57739. this._targetIndex = 0;
  57740. this._currentRenderId = -1;
  57741. this._started = false;
  57742. this._stopped = false;
  57743. this._timeDelta = 0;
  57744. this._attributesStrideSize = 16;
  57745. this._actualFrame = 0;
  57746. /**
  57747. * List of animations used by the particle system.
  57748. */
  57749. this.animations = [];
  57750. /**
  57751. * An event triggered when the system is disposed.
  57752. */
  57753. this.onDisposeObservable = new BABYLON.Observable();
  57754. /**
  57755. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57756. */
  57757. this.updateSpeed = 0.01;
  57758. /**
  57759. * The amount of time the particle system is running (depends of the overall update speed).
  57760. */
  57761. this.targetStopDuration = 0;
  57762. /**
  57763. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57764. */
  57765. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57766. /**
  57767. * Minimum life time of emitting particles.
  57768. */
  57769. this.minLifeTime = 1;
  57770. /**
  57771. * Maximum life time of emitting particles.
  57772. */
  57773. this.maxLifeTime = 1;
  57774. /**
  57775. * Minimum Size of emitting particles.
  57776. */
  57777. this.minSize = 1;
  57778. /**
  57779. * Maximum Size of emitting particles.
  57780. */
  57781. this.maxSize = 1;
  57782. /**
  57783. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57784. */
  57785. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57786. /**
  57787. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57788. */
  57789. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57790. /**
  57791. * Color the particle will have at the end of its lifetime.
  57792. */
  57793. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57794. /**
  57795. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57796. */
  57797. this.emitRate = 100;
  57798. /**
  57799. * You can use gravity if you want to give an orientation to your particles.
  57800. */
  57801. this.gravity = BABYLON.Vector3.Zero();
  57802. /**
  57803. * Minimum power of emitting particles.
  57804. */
  57805. this.minEmitPower = 1;
  57806. /**
  57807. * Maximum power of emitting particles.
  57808. */
  57809. this.maxEmitPower = 1;
  57810. /**
  57811. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57812. */
  57813. this.minAngularSpeed = 0;
  57814. /**
  57815. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57816. */
  57817. this.maxAngularSpeed = 0;
  57818. /**
  57819. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57820. * to override the particles.
  57821. */
  57822. this.forceDepthWrite = false;
  57823. this.id = name;
  57824. this.name = name;
  57825. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57826. this._engine = this._scene.getEngine();
  57827. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57828. this._capacity = fullOptions.capacity;
  57829. this._activeCount = fullOptions.capacity;
  57830. this._currentActiveCount = 0;
  57831. this._scene.particleSystems.push(this);
  57832. this._updateEffectOptions = {
  57833. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57834. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57835. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57836. "angleRange"],
  57837. uniformBuffersNames: [],
  57838. samplers: ["randomSampler"],
  57839. defines: "",
  57840. fallbacks: null,
  57841. onCompiled: null,
  57842. onError: null,
  57843. indexParameters: null,
  57844. maxSimultaneousLights: 0,
  57845. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57846. };
  57847. // Random data
  57848. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57849. var d = [];
  57850. for (var i = 0; i < maxTextureSize; ++i) {
  57851. d.push(Math.random());
  57852. d.push(Math.random());
  57853. d.push(Math.random());
  57854. d.push(Math.random());
  57855. }
  57856. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57857. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57858. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57859. this._randomTextureSize = maxTextureSize;
  57860. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57861. }
  57862. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57863. /**
  57864. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57865. */
  57866. get: function () {
  57867. if (!BABYLON.Engine.LastCreatedEngine) {
  57868. return false;
  57869. }
  57870. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57871. },
  57872. enumerable: true,
  57873. configurable: true
  57874. });
  57875. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57876. /**
  57877. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57878. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57879. */
  57880. get: function () {
  57881. if (this.particleEmitterType.direction1) {
  57882. return this.particleEmitterType.direction1;
  57883. }
  57884. return BABYLON.Vector3.Zero();
  57885. },
  57886. set: function (value) {
  57887. if (this.particleEmitterType.direction1) {
  57888. this.particleEmitterType.direction1 = value;
  57889. }
  57890. },
  57891. enumerable: true,
  57892. configurable: true
  57893. });
  57894. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57895. /**
  57896. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57897. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57898. */
  57899. get: function () {
  57900. if (this.particleEmitterType.direction2) {
  57901. return this.particleEmitterType.direction2;
  57902. }
  57903. return BABYLON.Vector3.Zero();
  57904. },
  57905. set: function (value) {
  57906. if (this.particleEmitterType.direction2) {
  57907. this.particleEmitterType.direction2 = value;
  57908. }
  57909. },
  57910. enumerable: true,
  57911. configurable: true
  57912. });
  57913. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57914. /**
  57915. * 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.
  57916. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57917. */
  57918. get: function () {
  57919. if (this.particleEmitterType.minEmitBox) {
  57920. return this.particleEmitterType.minEmitBox;
  57921. }
  57922. return BABYLON.Vector3.Zero();
  57923. },
  57924. set: function (value) {
  57925. if (this.particleEmitterType.minEmitBox) {
  57926. this.particleEmitterType.minEmitBox = value;
  57927. }
  57928. },
  57929. enumerable: true,
  57930. configurable: true
  57931. });
  57932. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57933. /**
  57934. * 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.
  57935. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57936. */
  57937. get: function () {
  57938. if (this.particleEmitterType.maxEmitBox) {
  57939. return this.particleEmitterType.maxEmitBox;
  57940. }
  57941. return BABYLON.Vector3.Zero();
  57942. },
  57943. set: function (value) {
  57944. if (this.particleEmitterType.maxEmitBox) {
  57945. this.particleEmitterType.maxEmitBox = value;
  57946. }
  57947. },
  57948. enumerable: true,
  57949. configurable: true
  57950. });
  57951. /**
  57952. * Gets the maximum number of particles active at the same time.
  57953. * @returns The max number of active particles.
  57954. */
  57955. GPUParticleSystem.prototype.getCapacity = function () {
  57956. return this._capacity;
  57957. };
  57958. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57959. /**
  57960. * Gets or set the number of active particles
  57961. */
  57962. get: function () {
  57963. return this._activeCount;
  57964. },
  57965. set: function (value) {
  57966. this._activeCount = Math.min(value, this._capacity);
  57967. },
  57968. enumerable: true,
  57969. configurable: true
  57970. });
  57971. /**
  57972. * Is this system ready to be used/rendered
  57973. * @return true if the system is ready
  57974. */
  57975. GPUParticleSystem.prototype.isReady = function () {
  57976. if (!this._updateEffect) {
  57977. this._recreateUpdateEffect();
  57978. this._recreateRenderEffect();
  57979. return false;
  57980. }
  57981. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57982. return false;
  57983. }
  57984. return true;
  57985. };
  57986. /**
  57987. * Gets Wether the system has been started.
  57988. * @returns True if it has been started, otherwise false.
  57989. */
  57990. GPUParticleSystem.prototype.isStarted = function () {
  57991. return this._started;
  57992. };
  57993. /**
  57994. * Starts the particle system and begins to emit.
  57995. */
  57996. GPUParticleSystem.prototype.start = function () {
  57997. this._started = true;
  57998. this._stopped = false;
  57999. };
  58000. /**
  58001. * Stops the particle system.
  58002. */
  58003. GPUParticleSystem.prototype.stop = function () {
  58004. this._stopped = true;
  58005. };
  58006. /**
  58007. * Remove all active particles
  58008. */
  58009. GPUParticleSystem.prototype.reset = function () {
  58010. this._releaseBuffers();
  58011. this._releaseVAOs();
  58012. this._currentActiveCount = 0;
  58013. this._targetIndex = 0;
  58014. };
  58015. /**
  58016. * Returns the string "GPUParticleSystem"
  58017. * @returns a string containing the class name
  58018. */
  58019. GPUParticleSystem.prototype.getClassName = function () {
  58020. return "GPUParticleSystem";
  58021. };
  58022. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  58023. var updateVertexBuffers = {};
  58024. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  58025. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  58026. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  58027. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  58028. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  58029. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  58030. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  58031. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  58032. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  58033. this._engine.bindArrayBuffer(null);
  58034. return vao;
  58035. };
  58036. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  58037. var renderVertexBuffers = {};
  58038. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  58039. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  58040. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  58041. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  58042. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  58043. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  58044. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  58045. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  58046. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  58047. this._engine.bindArrayBuffer(null);
  58048. return vao;
  58049. };
  58050. GPUParticleSystem.prototype._initialize = function (force) {
  58051. if (force === void 0) { force = false; }
  58052. if (this._buffer0 && !force) {
  58053. return;
  58054. }
  58055. var engine = this._scene.getEngine();
  58056. var data = new Array();
  58057. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  58058. // position
  58059. data.push(0.0);
  58060. data.push(0.0);
  58061. data.push(0.0);
  58062. // Age and life
  58063. data.push(0.0); // create the particle as a dead one to create a new one at start
  58064. data.push(0.0);
  58065. // Seed
  58066. data.push(Math.random());
  58067. // Size
  58068. data.push(0.0);
  58069. // color
  58070. data.push(0.0);
  58071. data.push(0.0);
  58072. data.push(0.0);
  58073. data.push(0.0);
  58074. // direction
  58075. data.push(0.0);
  58076. data.push(0.0);
  58077. data.push(0.0);
  58078. // angle
  58079. data.push(0.0);
  58080. data.push(0.0);
  58081. }
  58082. // Sprite data
  58083. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  58084. -0.5, 0.5, 0, 1,
  58085. -0.5, -0.5, 0, 0,
  58086. 0.5, -0.5, 1, 0]);
  58087. // Buffers
  58088. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58089. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58090. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  58091. // Update VAO
  58092. this._updateVAO = [];
  58093. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58094. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58095. // Render VAO
  58096. this._renderVAO = [];
  58097. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58098. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58099. // Links
  58100. this._sourceBuffer = this._buffer0;
  58101. this._targetBuffer = this._buffer1;
  58102. };
  58103. /** @hidden */
  58104. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58105. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58106. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58107. return;
  58108. }
  58109. this._updateEffectOptions.defines = defines;
  58110. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58111. };
  58112. /** @hidden */
  58113. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58114. var defines = "";
  58115. if (this._scene.clipPlane) {
  58116. defines = "\n#define CLIPPLANE";
  58117. }
  58118. if (this._renderEffect && this._renderEffect.defines === defines) {
  58119. return;
  58120. }
  58121. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58122. };
  58123. /**
  58124. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58125. */
  58126. GPUParticleSystem.prototype.animate = function () {
  58127. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58128. this._actualFrame += this._timeDelta;
  58129. if (!this._stopped) {
  58130. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58131. this.stop();
  58132. }
  58133. }
  58134. };
  58135. /**
  58136. * Renders the particle system in its current state.
  58137. * @returns the current number of particles
  58138. */
  58139. GPUParticleSystem.prototype.render = function () {
  58140. if (!this._started) {
  58141. return 0;
  58142. }
  58143. this._recreateUpdateEffect();
  58144. this._recreateRenderEffect();
  58145. if (!this.isReady()) {
  58146. return 0;
  58147. }
  58148. if (this._currentRenderId === this._scene.getRenderId()) {
  58149. return 0;
  58150. }
  58151. this._currentRenderId = this._scene.getRenderId();
  58152. // Get everything ready to render
  58153. this._initialize();
  58154. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58155. // Enable update effect
  58156. this._engine.enableEffect(this._updateEffect);
  58157. this._engine.setState(false);
  58158. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58159. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58160. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58161. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58162. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58163. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58164. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58165. this._updateEffect.setDirectColor4("color1", this.color1);
  58166. this._updateEffect.setDirectColor4("color2", this.color2);
  58167. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58168. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58169. this._updateEffect.setVector3("gravity", this.gravity);
  58170. if (this.particleEmitterType) {
  58171. this.particleEmitterType.applyToShader(this._updateEffect);
  58172. }
  58173. var emitterWM;
  58174. if (this.emitter.position) {
  58175. var emitterMesh = this.emitter;
  58176. emitterWM = emitterMesh.getWorldMatrix();
  58177. }
  58178. else {
  58179. var emitterPosition = this.emitter;
  58180. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58181. }
  58182. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58183. // Bind source VAO
  58184. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58185. // Update
  58186. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58187. this._engine.setRasterizerState(false);
  58188. this._engine.beginTransformFeedback();
  58189. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58190. this._engine.endTransformFeedback();
  58191. this._engine.setRasterizerState(true);
  58192. this._engine.bindTransformFeedbackBuffer(null);
  58193. // Enable render effect
  58194. this._engine.enableEffect(this._renderEffect);
  58195. var viewMatrix = this._scene.getViewMatrix();
  58196. this._renderEffect.setMatrix("view", viewMatrix);
  58197. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58198. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58199. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58200. if (this._scene.clipPlane) {
  58201. var clipPlane = this._scene.clipPlane;
  58202. var invView = viewMatrix.clone();
  58203. invView.invert();
  58204. this._renderEffect.setMatrix("invView", invView);
  58205. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58206. }
  58207. // Draw order
  58208. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58209. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58210. }
  58211. else {
  58212. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58213. }
  58214. if (this.forceDepthWrite) {
  58215. this._engine.setDepthWrite(true);
  58216. }
  58217. // Bind source VAO
  58218. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58219. // Render
  58220. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58221. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58222. // Switch VAOs
  58223. this._targetIndex++;
  58224. if (this._targetIndex === 2) {
  58225. this._targetIndex = 0;
  58226. }
  58227. // Switch buffers
  58228. var tmpBuffer = this._sourceBuffer;
  58229. this._sourceBuffer = this._targetBuffer;
  58230. this._targetBuffer = tmpBuffer;
  58231. return this._currentActiveCount;
  58232. };
  58233. /**
  58234. * Rebuilds the particle system
  58235. */
  58236. GPUParticleSystem.prototype.rebuild = function () {
  58237. this._initialize(true);
  58238. };
  58239. GPUParticleSystem.prototype._releaseBuffers = function () {
  58240. if (this._buffer0) {
  58241. this._buffer0.dispose();
  58242. this._buffer0 = null;
  58243. }
  58244. if (this._buffer1) {
  58245. this._buffer1.dispose();
  58246. this._buffer1 = null;
  58247. }
  58248. if (this._spriteBuffer) {
  58249. this._spriteBuffer.dispose();
  58250. this._spriteBuffer = null;
  58251. }
  58252. };
  58253. GPUParticleSystem.prototype._releaseVAOs = function () {
  58254. if (!this._updateVAO) {
  58255. return;
  58256. }
  58257. for (var index = 0; index < this._updateVAO.length; index++) {
  58258. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58259. }
  58260. this._updateVAO = [];
  58261. for (var index = 0; index < this._renderVAO.length; index++) {
  58262. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58263. }
  58264. this._renderVAO = [];
  58265. };
  58266. /**
  58267. * Disposes the particle system and free the associated resources
  58268. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58269. */
  58270. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58271. if (disposeTexture === void 0) { disposeTexture = true; }
  58272. var index = this._scene.particleSystems.indexOf(this);
  58273. if (index > -1) {
  58274. this._scene.particleSystems.splice(index, 1);
  58275. }
  58276. this._releaseBuffers();
  58277. this._releaseVAOs();
  58278. if (this._randomTexture) {
  58279. this._randomTexture.dispose();
  58280. this._randomTexture = null;
  58281. }
  58282. if (disposeTexture && this.particleTexture) {
  58283. this.particleTexture.dispose();
  58284. this.particleTexture = null;
  58285. }
  58286. // Callback
  58287. this.onDisposeObservable.notifyObservers(this);
  58288. this.onDisposeObservable.clear();
  58289. };
  58290. /**
  58291. * Clones the particle system.
  58292. * @param name The name of the cloned object
  58293. * @param newEmitter The new emitter to use
  58294. * @returns the cloned particle system
  58295. */
  58296. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58297. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58298. BABYLON.Tools.DeepCopy(this, result);
  58299. if (newEmitter === undefined) {
  58300. newEmitter = this.emitter;
  58301. }
  58302. result.emitter = newEmitter;
  58303. if (this.particleTexture) {
  58304. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58305. }
  58306. return result;
  58307. };
  58308. /**
  58309. * Serializes the particle system to a JSON object.
  58310. * @returns the JSON object
  58311. */
  58312. GPUParticleSystem.prototype.serialize = function () {
  58313. var serializationObject = {};
  58314. serializationObject.name = this.name;
  58315. serializationObject.id = this.id;
  58316. // Emitter
  58317. if (this.emitter.position) {
  58318. var emitterMesh = this.emitter;
  58319. serializationObject.emitterId = emitterMesh.id;
  58320. }
  58321. else {
  58322. var emitterPosition = this.emitter;
  58323. serializationObject.emitter = emitterPosition.asArray();
  58324. }
  58325. serializationObject.capacity = this.getCapacity();
  58326. if (this.particleTexture) {
  58327. serializationObject.textureName = this.particleTexture.name;
  58328. }
  58329. // Animations
  58330. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58331. // Particle system
  58332. serializationObject.activeParticleCount = this.activeParticleCount;
  58333. serializationObject.randomTextureSize = this._randomTextureSize;
  58334. serializationObject.minSize = this.minSize;
  58335. serializationObject.maxSize = this.maxSize;
  58336. serializationObject.minEmitPower = this.minEmitPower;
  58337. serializationObject.maxEmitPower = this.maxEmitPower;
  58338. serializationObject.minLifeTime = this.minLifeTime;
  58339. serializationObject.maxLifeTime = this.maxLifeTime;
  58340. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58341. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58342. serializationObject.emitRate = this.emitRate;
  58343. serializationObject.gravity = this.gravity.asArray();
  58344. serializationObject.color1 = this.color1.asArray();
  58345. serializationObject.color2 = this.color2.asArray();
  58346. serializationObject.colorDead = this.colorDead.asArray();
  58347. serializationObject.updateSpeed = this.updateSpeed;
  58348. serializationObject.targetStopDuration = this.targetStopDuration;
  58349. serializationObject.blendMode = this.blendMode;
  58350. // Emitter
  58351. if (this.particleEmitterType) {
  58352. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58353. }
  58354. return serializationObject;
  58355. };
  58356. /**
  58357. * Parses a JSON object to create a GPU particle system.
  58358. * @param parsedParticleSystem The JSON object to parse
  58359. * @param scene The scene to create the particle system in
  58360. * @param rootUrl The root url to use to load external dependencies like texture
  58361. * @returns the parsed GPU particle system
  58362. */
  58363. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58364. var name = parsedParticleSystem.name;
  58365. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58366. if (parsedParticleSystem.id) {
  58367. particleSystem.id = parsedParticleSystem.id;
  58368. }
  58369. // Texture
  58370. if (parsedParticleSystem.textureName) {
  58371. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58372. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58373. }
  58374. // Emitter
  58375. if (parsedParticleSystem.emitterId) {
  58376. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58377. }
  58378. else {
  58379. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58380. }
  58381. // Animations
  58382. if (parsedParticleSystem.animations) {
  58383. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58384. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58385. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58386. }
  58387. }
  58388. // Particle system
  58389. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58390. particleSystem.minSize = parsedParticleSystem.minSize;
  58391. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58392. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58393. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58394. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58395. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58396. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58397. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58398. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58399. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58400. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58401. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58402. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58403. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58404. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58405. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58406. // Emitter
  58407. if (parsedParticleSystem.particleEmitterType) {
  58408. var emitterType = void 0;
  58409. switch (parsedParticleSystem.particleEmitterType.type) {
  58410. case "SphereEmitter":
  58411. emitterType = new BABYLON.SphereParticleEmitter();
  58412. break;
  58413. case "SphereDirectedParticleEmitter":
  58414. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58415. break;
  58416. case "ConeEmitter":
  58417. emitterType = new BABYLON.ConeParticleEmitter();
  58418. break;
  58419. case "BoxEmitter":
  58420. default:
  58421. emitterType = new BABYLON.BoxParticleEmitter();
  58422. break;
  58423. }
  58424. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58425. particleSystem.particleEmitterType = emitterType;
  58426. }
  58427. return particleSystem;
  58428. };
  58429. return GPUParticleSystem;
  58430. }());
  58431. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58432. })(BABYLON || (BABYLON = {}));
  58433. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58434. var BABYLON;
  58435. (function (BABYLON) {
  58436. /**
  58437. * Represents one particle of a solid particle system.
  58438. */
  58439. var SolidParticle = /** @class */ (function () {
  58440. /**
  58441. * Creates a Solid Particle object.
  58442. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58443. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58444. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58445. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58446. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58447. * @param shapeId (integer) is the model shape identifier in the SPS.
  58448. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58449. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58450. */
  58451. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58452. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58453. /**
  58454. * particle global index
  58455. */
  58456. this.idx = 0;
  58457. /**
  58458. * The color of the particle
  58459. */
  58460. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58461. /**
  58462. * The world space position of the particle.
  58463. */
  58464. this.position = BABYLON.Vector3.Zero();
  58465. /**
  58466. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58467. */
  58468. this.rotation = BABYLON.Vector3.Zero();
  58469. /**
  58470. * The scaling of the particle.
  58471. */
  58472. this.scaling = BABYLON.Vector3.One();
  58473. /**
  58474. * The uvs of the particle.
  58475. */
  58476. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58477. /**
  58478. * The current speed of the particle.
  58479. */
  58480. this.velocity = BABYLON.Vector3.Zero();
  58481. /**
  58482. * The pivot point in the particle local space.
  58483. */
  58484. this.pivot = BABYLON.Vector3.Zero();
  58485. /**
  58486. * Must the particle be translated from its pivot point in its local space ?
  58487. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58488. * Default : false
  58489. */
  58490. this.translateFromPivot = false;
  58491. /**
  58492. * Is the particle active or not ?
  58493. */
  58494. this.alive = true;
  58495. /**
  58496. * Is the particle visible or not ?
  58497. */
  58498. this.isVisible = true;
  58499. /**
  58500. * Index of this particle in the global "positions" array (Internal use)
  58501. */
  58502. this._pos = 0;
  58503. /**
  58504. * Index of this particle in the global "indices" array (Internal use)
  58505. */
  58506. this._ind = 0;
  58507. /**
  58508. * ModelShape id of this particle
  58509. */
  58510. this.shapeId = 0;
  58511. /**
  58512. * Index of the particle in its shape id (Internal use)
  58513. */
  58514. this.idxInShape = 0;
  58515. /**
  58516. * Still set as invisible in order to skip useless computations (Internal use)
  58517. */
  58518. this._stillInvisible = false;
  58519. /**
  58520. * Last computed particle rotation matrix
  58521. */
  58522. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58523. /**
  58524. * Parent particle Id, if any.
  58525. * Default null.
  58526. */
  58527. this.parentId = null;
  58528. /**
  58529. * Internal global position in the SPS.
  58530. */
  58531. this._globalPosition = BABYLON.Vector3.Zero();
  58532. this.idx = particleIndex;
  58533. this._pos = positionIndex;
  58534. this._ind = indiceIndex;
  58535. this._model = model;
  58536. this.shapeId = shapeId;
  58537. this.idxInShape = idxInShape;
  58538. this._sps = sps;
  58539. if (modelBoundingInfo) {
  58540. this._modelBoundingInfo = modelBoundingInfo;
  58541. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58542. }
  58543. }
  58544. Object.defineProperty(SolidParticle.prototype, "scale", {
  58545. /**
  58546. * Legacy support, changed scale to scaling
  58547. */
  58548. get: function () {
  58549. return this.scaling;
  58550. },
  58551. /**
  58552. * Legacy support, changed scale to scaling
  58553. */
  58554. set: function (scale) {
  58555. this.scaling = scale;
  58556. },
  58557. enumerable: true,
  58558. configurable: true
  58559. });
  58560. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58561. /**
  58562. * Legacy support, changed quaternion to rotationQuaternion
  58563. */
  58564. get: function () {
  58565. return this.rotationQuaternion;
  58566. },
  58567. /**
  58568. * Legacy support, changed quaternion to rotationQuaternion
  58569. */
  58570. set: function (q) {
  58571. this.rotationQuaternion = q;
  58572. },
  58573. enumerable: true,
  58574. configurable: true
  58575. });
  58576. /**
  58577. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58578. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58579. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58580. * @returns true if it intersects
  58581. */
  58582. SolidParticle.prototype.intersectsMesh = function (target) {
  58583. if (!this._boundingInfo || !target._boundingInfo) {
  58584. return false;
  58585. }
  58586. if (this._sps._bSphereOnly) {
  58587. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58588. }
  58589. return this._boundingInfo.intersects(target._boundingInfo, false);
  58590. };
  58591. return SolidParticle;
  58592. }());
  58593. BABYLON.SolidParticle = SolidParticle;
  58594. /**
  58595. * Represents the shape of the model used by one particle of a solid particle system.
  58596. * SPS internal tool, don't use it manually.
  58597. */
  58598. var ModelShape = /** @class */ (function () {
  58599. /**
  58600. * 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.
  58601. * SPS internal tool, don't use it manually.
  58602. * @hidden
  58603. */
  58604. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58605. /**
  58606. * length of the shape in the model indices array (internal use)
  58607. */
  58608. this._indicesLength = 0;
  58609. this.shapeID = id;
  58610. this._shape = shape;
  58611. this._indicesLength = indicesLength;
  58612. this._shapeUV = shapeUV;
  58613. this._positionFunction = posFunction;
  58614. this._vertexFunction = vtxFunction;
  58615. }
  58616. return ModelShape;
  58617. }());
  58618. BABYLON.ModelShape = ModelShape;
  58619. /**
  58620. * Represents a Depth Sorted Particle in the solid particle system.
  58621. */
  58622. var DepthSortedParticle = /** @class */ (function () {
  58623. function DepthSortedParticle() {
  58624. /**
  58625. * Index of the particle in the "indices" array
  58626. */
  58627. this.ind = 0;
  58628. /**
  58629. * Length of the particle shape in the "indices" array
  58630. */
  58631. this.indicesLength = 0;
  58632. /**
  58633. * Squared distance from the particle to the camera
  58634. */
  58635. this.sqDistance = 0.0;
  58636. }
  58637. return DepthSortedParticle;
  58638. }());
  58639. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58640. })(BABYLON || (BABYLON = {}));
  58641. //# sourceMappingURL=babylon.solidParticle.js.map
  58642. var BABYLON;
  58643. (function (BABYLON) {
  58644. /**
  58645. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58646. *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.
  58647. * The SPS is also a particle system. It provides some methods to manage the particles.
  58648. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58649. *
  58650. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58651. */
  58652. var SolidParticleSystem = /** @class */ (function () {
  58653. /**
  58654. * Creates a SPS (Solid Particle System) object.
  58655. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58656. * @param scene (Scene) is the scene in which the SPS is added.
  58657. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58658. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58659. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58660. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58661. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58662. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58663. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58664. */
  58665. function SolidParticleSystem(name, scene, options) {
  58666. /**
  58667. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58668. * Example : var p = SPS.particles[i];
  58669. */
  58670. this.particles = new Array();
  58671. /**
  58672. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58673. */
  58674. this.nbParticles = 0;
  58675. /**
  58676. * If the particles must ever face the camera (default false). Useful for planar particles.
  58677. */
  58678. this.billboard = false;
  58679. /**
  58680. * Recompute normals when adding a shape
  58681. */
  58682. this.recomputeNormals = true;
  58683. /**
  58684. * This a counter ofr your own usage. It's not set by any SPS functions.
  58685. */
  58686. this.counter = 0;
  58687. /**
  58688. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58689. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58690. */
  58691. this.vars = {};
  58692. /**
  58693. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58694. */
  58695. this._bSphereOnly = false;
  58696. /**
  58697. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58698. */
  58699. this._bSphereRadiusFactor = 1.0;
  58700. this._positions = new Array();
  58701. this._indices = new Array();
  58702. this._normals = new Array();
  58703. this._colors = new Array();
  58704. this._uvs = new Array();
  58705. this._index = 0; // indices index
  58706. this._updatable = true;
  58707. this._pickable = false;
  58708. this._isVisibilityBoxLocked = false;
  58709. this._alwaysVisible = false;
  58710. this._depthSort = false;
  58711. this._shapeCounter = 0;
  58712. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58713. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58714. this._computeParticleColor = true;
  58715. this._computeParticleTexture = true;
  58716. this._computeParticleRotation = true;
  58717. this._computeParticleVertex = false;
  58718. this._computeBoundingBox = false;
  58719. this._depthSortParticles = true;
  58720. this._cam_axisZ = BABYLON.Vector3.Zero();
  58721. this._cam_axisY = BABYLON.Vector3.Zero();
  58722. this._cam_axisX = BABYLON.Vector3.Zero();
  58723. this._axisZ = BABYLON.Axis.Z;
  58724. this._camDir = BABYLON.Vector3.Zero();
  58725. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58726. this._rotMatrix = new BABYLON.Matrix();
  58727. this._invertMatrix = new BABYLON.Matrix();
  58728. this._rotated = BABYLON.Vector3.Zero();
  58729. this._quaternion = new BABYLON.Quaternion();
  58730. this._vertex = BABYLON.Vector3.Zero();
  58731. this._normal = BABYLON.Vector3.Zero();
  58732. this._yaw = 0.0;
  58733. this._pitch = 0.0;
  58734. this._roll = 0.0;
  58735. this._halfroll = 0.0;
  58736. this._halfpitch = 0.0;
  58737. this._halfyaw = 0.0;
  58738. this._sinRoll = 0.0;
  58739. this._cosRoll = 0.0;
  58740. this._sinPitch = 0.0;
  58741. this._cosPitch = 0.0;
  58742. this._sinYaw = 0.0;
  58743. this._cosYaw = 0.0;
  58744. this._mustUnrotateFixedNormals = false;
  58745. this._minimum = BABYLON.Vector3.Zero();
  58746. this._maximum = BABYLON.Vector3.Zero();
  58747. this._minBbox = BABYLON.Vector3.Zero();
  58748. this._maxBbox = BABYLON.Vector3.Zero();
  58749. this._particlesIntersect = false;
  58750. this._depthSortFunction = function (p1, p2) {
  58751. return (p2.sqDistance - p1.sqDistance);
  58752. };
  58753. this._needs32Bits = false;
  58754. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58755. this._scaledPivot = BABYLON.Vector3.Zero();
  58756. this._particleHasParent = false;
  58757. this.name = name;
  58758. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58759. this._camera = scene.activeCamera;
  58760. this._pickable = options ? options.isPickable : false;
  58761. this._depthSort = options ? options.enableDepthSort : false;
  58762. this._particlesIntersect = options ? options.particleIntersection : false;
  58763. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58764. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58765. if (options && options.updatable) {
  58766. this._updatable = options.updatable;
  58767. }
  58768. else {
  58769. this._updatable = true;
  58770. }
  58771. if (this._pickable) {
  58772. this.pickedParticles = [];
  58773. }
  58774. if (this._depthSort) {
  58775. this.depthSortedParticles = [];
  58776. }
  58777. }
  58778. /**
  58779. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58780. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58781. * @returns the created mesh
  58782. */
  58783. SolidParticleSystem.prototype.buildMesh = function () {
  58784. if (this.nbParticles === 0) {
  58785. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58786. this.addShape(triangle, 1);
  58787. triangle.dispose();
  58788. }
  58789. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58790. this._positions32 = new Float32Array(this._positions);
  58791. this._uvs32 = new Float32Array(this._uvs);
  58792. this._colors32 = new Float32Array(this._colors);
  58793. if (this.recomputeNormals) {
  58794. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58795. }
  58796. this._normals32 = new Float32Array(this._normals);
  58797. this._fixedNormal32 = new Float32Array(this._normals);
  58798. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58799. this._unrotateFixedNormals();
  58800. }
  58801. var vertexData = new BABYLON.VertexData();
  58802. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58803. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58804. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58805. if (this._uvs32.length > 0) {
  58806. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58807. }
  58808. if (this._colors32.length > 0) {
  58809. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58810. }
  58811. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58812. vertexData.applyToMesh(mesh, this._updatable);
  58813. this.mesh = mesh;
  58814. this.mesh.isPickable = this._pickable;
  58815. // free memory
  58816. if (!this._depthSort) {
  58817. this._indices = null;
  58818. }
  58819. this._positions = null;
  58820. this._normals = null;
  58821. this._uvs = null;
  58822. this._colors = null;
  58823. if (!this._updatable) {
  58824. this.particles.length = 0;
  58825. }
  58826. return mesh;
  58827. };
  58828. /**
  58829. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58830. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58831. * Thus the particles generated from `digest()` have their property `position` set yet.
  58832. * @param mesh ( Mesh ) is the mesh to be digested
  58833. * @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
  58834. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58835. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58836. * @returns the current SPS
  58837. */
  58838. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58839. var size = (options && options.facetNb) || 1;
  58840. var number = (options && options.number) || 0;
  58841. var delta = (options && options.delta) || 0;
  58842. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58843. var meshInd = mesh.getIndices();
  58844. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58845. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58846. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58847. var f = 0; // facet counter
  58848. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58849. // compute size from number
  58850. if (number) {
  58851. number = (number > totalFacets) ? totalFacets : number;
  58852. size = Math.round(totalFacets / number);
  58853. delta = 0;
  58854. }
  58855. else {
  58856. size = (size > totalFacets) ? totalFacets : size;
  58857. }
  58858. var facetPos = []; // submesh positions
  58859. var facetInd = []; // submesh indices
  58860. var facetUV = []; // submesh UV
  58861. var facetCol = []; // submesh colors
  58862. var barycenter = BABYLON.Vector3.Zero();
  58863. var sizeO = size;
  58864. while (f < totalFacets) {
  58865. size = sizeO + Math.floor((1 + delta) * Math.random());
  58866. if (f > totalFacets - size) {
  58867. size = totalFacets - f;
  58868. }
  58869. // reset temp arrays
  58870. facetPos.length = 0;
  58871. facetInd.length = 0;
  58872. facetUV.length = 0;
  58873. facetCol.length = 0;
  58874. // iterate over "size" facets
  58875. var fi = 0;
  58876. for (var j = f * 3; j < (f + size) * 3; j++) {
  58877. facetInd.push(fi);
  58878. var i = meshInd[j];
  58879. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58880. if (meshUV) {
  58881. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58882. }
  58883. if (meshCol) {
  58884. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58885. }
  58886. fi++;
  58887. }
  58888. // create a model shape for each single particle
  58889. var idx = this.nbParticles;
  58890. var shape = this._posToShape(facetPos);
  58891. var shapeUV = this._uvsToShapeUV(facetUV);
  58892. // compute the barycenter of the shape
  58893. var v;
  58894. for (v = 0; v < shape.length; v++) {
  58895. barycenter.addInPlace(shape[v]);
  58896. }
  58897. barycenter.scaleInPlace(1 / shape.length);
  58898. // shift the shape from its barycenter to the origin
  58899. for (v = 0; v < shape.length; v++) {
  58900. shape[v].subtractInPlace(barycenter);
  58901. }
  58902. var bInfo;
  58903. if (this._particlesIntersect) {
  58904. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58905. }
  58906. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58907. // add the particle in the SPS
  58908. var currentPos = this._positions.length;
  58909. var currentInd = this._indices.length;
  58910. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58911. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58912. // initialize the particle position
  58913. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58914. this._index += shape.length;
  58915. idx++;
  58916. this.nbParticles++;
  58917. this._shapeCounter++;
  58918. f += size;
  58919. }
  58920. return this;
  58921. };
  58922. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58923. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58924. var index = 0;
  58925. var idx = 0;
  58926. for (var p = 0; p < this.particles.length; p++) {
  58927. this._particle = this.particles[p];
  58928. this._shape = this._particle._model._shape;
  58929. if (this._particle.rotationQuaternion) {
  58930. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58931. }
  58932. else {
  58933. this._yaw = this._particle.rotation.y;
  58934. this._pitch = this._particle.rotation.x;
  58935. this._roll = this._particle.rotation.z;
  58936. this._quaternionRotationYPR();
  58937. }
  58938. this._quaternionToRotationMatrix();
  58939. this._rotMatrix.invertToRef(this._invertMatrix);
  58940. for (var pt = 0; pt < this._shape.length; pt++) {
  58941. idx = index + pt * 3;
  58942. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58943. this._fixedNormal32[idx] = this._normal.x;
  58944. this._fixedNormal32[idx + 1] = this._normal.y;
  58945. this._fixedNormal32[idx + 2] = this._normal.z;
  58946. }
  58947. index = idx + 3;
  58948. }
  58949. };
  58950. //reset copy
  58951. SolidParticleSystem.prototype._resetCopy = function () {
  58952. this._copy.position.x = 0;
  58953. this._copy.position.y = 0;
  58954. this._copy.position.z = 0;
  58955. this._copy.rotation.x = 0;
  58956. this._copy.rotation.y = 0;
  58957. this._copy.rotation.z = 0;
  58958. this._copy.rotationQuaternion = null;
  58959. this._copy.scaling.x = 1.0;
  58960. this._copy.scaling.y = 1.0;
  58961. this._copy.scaling.z = 1.0;
  58962. this._copy.uvs.x = 0;
  58963. this._copy.uvs.y = 0;
  58964. this._copy.uvs.z = 1.0;
  58965. this._copy.uvs.w = 1.0;
  58966. this._copy.color = null;
  58967. this._copy.translateFromPivot = false;
  58968. };
  58969. // _meshBuilder : inserts the shape model in the global SPS mesh
  58970. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58971. var i;
  58972. var u = 0;
  58973. var c = 0;
  58974. var n = 0;
  58975. this._resetCopy();
  58976. if (options && options.positionFunction) { // call to custom positionFunction
  58977. options.positionFunction(this._copy, idx, idxInShape);
  58978. this._mustUnrotateFixedNormals = true;
  58979. }
  58980. if (this._copy.rotationQuaternion) {
  58981. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58982. }
  58983. else {
  58984. this._yaw = this._copy.rotation.y;
  58985. this._pitch = this._copy.rotation.x;
  58986. this._roll = this._copy.rotation.z;
  58987. this._quaternionRotationYPR();
  58988. }
  58989. this._quaternionToRotationMatrix();
  58990. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58991. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58992. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58993. if (this._copy.translateFromPivot) {
  58994. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58995. }
  58996. else {
  58997. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58998. }
  58999. for (i = 0; i < shape.length; i++) {
  59000. this._vertex.x = shape[i].x;
  59001. this._vertex.y = shape[i].y;
  59002. this._vertex.z = shape[i].z;
  59003. if (options && options.vertexFunction) {
  59004. options.vertexFunction(this._copy, this._vertex, i);
  59005. }
  59006. this._vertex.x *= this._copy.scaling.x;
  59007. this._vertex.y *= this._copy.scaling.y;
  59008. this._vertex.z *= this._copy.scaling.z;
  59009. this._vertex.x -= this._scaledPivot.x;
  59010. this._vertex.y -= this._scaledPivot.y;
  59011. this._vertex.z -= this._scaledPivot.z;
  59012. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59013. this._rotated.addInPlace(this._pivotBackTranslation);
  59014. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  59015. if (meshUV) {
  59016. 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);
  59017. u += 2;
  59018. }
  59019. if (this._copy.color) {
  59020. this._color = this._copy.color;
  59021. }
  59022. else if (meshCol && meshCol[c] !== undefined) {
  59023. this._color.r = meshCol[c];
  59024. this._color.g = meshCol[c + 1];
  59025. this._color.b = meshCol[c + 2];
  59026. this._color.a = meshCol[c + 3];
  59027. }
  59028. else {
  59029. this._color.r = 1.0;
  59030. this._color.g = 1.0;
  59031. this._color.b = 1.0;
  59032. this._color.a = 1.0;
  59033. }
  59034. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  59035. c += 4;
  59036. if (!this.recomputeNormals && meshNor) {
  59037. this._normal.x = meshNor[n];
  59038. this._normal.y = meshNor[n + 1];
  59039. this._normal.z = meshNor[n + 2];
  59040. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  59041. normals.push(this._normal.x, this._normal.y, this._normal.z);
  59042. n += 3;
  59043. }
  59044. }
  59045. for (i = 0; i < meshInd.length; i++) {
  59046. var current_ind = p + meshInd[i];
  59047. indices.push(current_ind);
  59048. if (current_ind > 65535) {
  59049. this._needs32Bits = true;
  59050. }
  59051. }
  59052. if (this._pickable) {
  59053. var nbfaces = meshInd.length / 3;
  59054. for (i = 0; i < nbfaces; i++) {
  59055. this.pickedParticles.push({ idx: idx, faceId: i });
  59056. }
  59057. }
  59058. if (this._depthSort) {
  59059. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  59060. }
  59061. return this._copy;
  59062. };
  59063. // returns a shape array from positions array
  59064. SolidParticleSystem.prototype._posToShape = function (positions) {
  59065. var shape = [];
  59066. for (var i = 0; i < positions.length; i += 3) {
  59067. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  59068. }
  59069. return shape;
  59070. };
  59071. // returns a shapeUV array from a Vector4 uvs
  59072. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  59073. var shapeUV = [];
  59074. if (uvs) {
  59075. for (var i = 0; i < uvs.length; i++)
  59076. shapeUV.push(uvs[i]);
  59077. }
  59078. return shapeUV;
  59079. };
  59080. // adds a new particle object in the particles array
  59081. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  59082. if (bInfo === void 0) { bInfo = null; }
  59083. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  59084. this.particles.push(sp);
  59085. return sp;
  59086. };
  59087. /**
  59088. * Adds some particles to the SPS from the model shape. Returns the shape id.
  59089. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  59090. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  59091. * @param nb (positive integer) the number of particles to be created from this model
  59092. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  59093. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59094. * @returns the number of shapes in the system
  59095. */
  59096. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59097. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59098. var meshInd = mesh.getIndices();
  59099. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59100. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59101. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59102. var bbInfo;
  59103. if (this._particlesIntersect) {
  59104. bbInfo = mesh.getBoundingInfo();
  59105. }
  59106. var shape = this._posToShape(meshPos);
  59107. var shapeUV = this._uvsToShapeUV(meshUV);
  59108. var posfunc = options ? options.positionFunction : null;
  59109. var vtxfunc = options ? options.vertexFunction : null;
  59110. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59111. // particles
  59112. var sp;
  59113. var currentCopy;
  59114. var idx = this.nbParticles;
  59115. for (var i = 0; i < nb; i++) {
  59116. var currentPos = this._positions.length;
  59117. var currentInd = this._indices.length;
  59118. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59119. if (this._updatable) {
  59120. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59121. sp.position.copyFrom(currentCopy.position);
  59122. sp.rotation.copyFrom(currentCopy.rotation);
  59123. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59124. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59125. }
  59126. if (currentCopy.color && sp.color) {
  59127. sp.color.copyFrom(currentCopy.color);
  59128. }
  59129. sp.scaling.copyFrom(currentCopy.scaling);
  59130. sp.uvs.copyFrom(currentCopy.uvs);
  59131. }
  59132. this._index += shape.length;
  59133. idx++;
  59134. }
  59135. this.nbParticles += nb;
  59136. this._shapeCounter++;
  59137. return this._shapeCounter - 1;
  59138. };
  59139. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59140. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59141. this._resetCopy();
  59142. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59143. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59144. }
  59145. if (this._copy.rotationQuaternion) {
  59146. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59147. }
  59148. else {
  59149. this._yaw = this._copy.rotation.y;
  59150. this._pitch = this._copy.rotation.x;
  59151. this._roll = this._copy.rotation.z;
  59152. this._quaternionRotationYPR();
  59153. }
  59154. this._quaternionToRotationMatrix();
  59155. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59156. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59157. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59158. if (this._copy.translateFromPivot) {
  59159. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59160. }
  59161. else {
  59162. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59163. }
  59164. this._shape = particle._model._shape;
  59165. for (var pt = 0; pt < this._shape.length; pt++) {
  59166. this._vertex.x = this._shape[pt].x;
  59167. this._vertex.y = this._shape[pt].y;
  59168. this._vertex.z = this._shape[pt].z;
  59169. if (particle._model._vertexFunction) {
  59170. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59171. }
  59172. this._vertex.x *= this._copy.scaling.x;
  59173. this._vertex.y *= this._copy.scaling.y;
  59174. this._vertex.z *= this._copy.scaling.z;
  59175. this._vertex.x -= this._scaledPivot.x;
  59176. this._vertex.y -= this._scaledPivot.y;
  59177. this._vertex.z -= this._scaledPivot.z;
  59178. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59179. this._rotated.addInPlace(this._pivotBackTranslation);
  59180. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59181. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59182. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59183. }
  59184. particle.position.x = 0.0;
  59185. particle.position.y = 0.0;
  59186. particle.position.z = 0.0;
  59187. particle.rotation.x = 0.0;
  59188. particle.rotation.y = 0.0;
  59189. particle.rotation.z = 0.0;
  59190. particle.rotationQuaternion = null;
  59191. particle.scaling.x = 1.0;
  59192. particle.scaling.y = 1.0;
  59193. particle.scaling.z = 1.0;
  59194. particle.uvs.x = 0.0;
  59195. particle.uvs.y = 0.0;
  59196. particle.uvs.z = 1.0;
  59197. particle.uvs.w = 1.0;
  59198. particle.pivot.x = 0.0;
  59199. particle.pivot.y = 0.0;
  59200. particle.pivot.z = 0.0;
  59201. particle.translateFromPivot = false;
  59202. particle.parentId = null;
  59203. };
  59204. /**
  59205. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59206. * @returns the SPS.
  59207. */
  59208. SolidParticleSystem.prototype.rebuildMesh = function () {
  59209. for (var p = 0; p < this.particles.length; p++) {
  59210. this._rebuildParticle(this.particles[p]);
  59211. }
  59212. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59213. return this;
  59214. };
  59215. /**
  59216. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59217. * This method calls `updateParticle()` for each particle of the SPS.
  59218. * For an animated SPS, it is usually called within the render loop.
  59219. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59220. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59221. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59222. * @returns the SPS.
  59223. */
  59224. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59225. if (start === void 0) { start = 0; }
  59226. if (end === void 0) { end = this.nbParticles - 1; }
  59227. if (update === void 0) { update = true; }
  59228. if (!this._updatable) {
  59229. return this;
  59230. }
  59231. // custom beforeUpdate
  59232. this.beforeUpdateParticles(start, end, update);
  59233. this._cam_axisX.x = 1.0;
  59234. this._cam_axisX.y = 0.0;
  59235. this._cam_axisX.z = 0.0;
  59236. this._cam_axisY.x = 0.0;
  59237. this._cam_axisY.y = 1.0;
  59238. this._cam_axisY.z = 0.0;
  59239. this._cam_axisZ.x = 0.0;
  59240. this._cam_axisZ.y = 0.0;
  59241. this._cam_axisZ.z = 1.0;
  59242. // cases when the World Matrix is to be computed first
  59243. if (this.billboard || this._depthSort) {
  59244. this.mesh.computeWorldMatrix(true);
  59245. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59246. }
  59247. // if the particles will always face the camera
  59248. if (this.billboard) {
  59249. // compute the camera position and un-rotate it by the current mesh rotation
  59250. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59251. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59252. this._cam_axisZ.normalize();
  59253. // same for camera up vector extracted from the cam view matrix
  59254. var view = this._camera.getViewMatrix(true);
  59255. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59256. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59257. this._cam_axisY.normalize();
  59258. this._cam_axisX.normalize();
  59259. }
  59260. // if depthSort, compute the camera global position in the mesh local system
  59261. if (this._depthSort) {
  59262. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59263. }
  59264. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59265. var idx = 0; // current position index in the global array positions32
  59266. var index = 0; // position start index in the global array positions32 of the current particle
  59267. var colidx = 0; // current color index in the global array colors32
  59268. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59269. var uvidx = 0; // current uv index in the global array uvs32
  59270. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59271. var pt = 0; // current index in the particle model shape
  59272. if (this.mesh.isFacetDataEnabled) {
  59273. this._computeBoundingBox = true;
  59274. }
  59275. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59276. if (this._computeBoundingBox) {
  59277. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59278. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59279. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59280. }
  59281. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59282. if (this.mesh._boundingInfo) {
  59283. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59284. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59285. }
  59286. }
  59287. }
  59288. // particle loop
  59289. index = this.particles[start]._pos;
  59290. var vpos = (index / 3) | 0;
  59291. colorIndex = vpos * 4;
  59292. uvIndex = vpos * 2;
  59293. for (var p = start; p <= end; p++) {
  59294. this._particle = this.particles[p];
  59295. this._shape = this._particle._model._shape;
  59296. this._shapeUV = this._particle._model._shapeUV;
  59297. // call to custom user function to update the particle properties
  59298. this.updateParticle(this._particle);
  59299. // camera-particle distance for depth sorting
  59300. if (this._depthSort && this._depthSortParticles) {
  59301. var dsp = this.depthSortedParticles[p];
  59302. dsp.ind = this._particle._ind;
  59303. dsp.indicesLength = this._particle._model._indicesLength;
  59304. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59305. }
  59306. // skip the computations for inactive or already invisible particles
  59307. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59308. // increment indexes for the next particle
  59309. pt = this._shape.length;
  59310. index += pt * 3;
  59311. colorIndex += pt * 4;
  59312. uvIndex += pt * 2;
  59313. continue;
  59314. }
  59315. if (this._particle.isVisible) {
  59316. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59317. this._particleHasParent = (this._particle.parentId !== null);
  59318. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59319. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59320. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59321. // particle rotation matrix
  59322. if (this.billboard) {
  59323. this._particle.rotation.x = 0.0;
  59324. this._particle.rotation.y = 0.0;
  59325. }
  59326. if (this._computeParticleRotation || this.billboard) {
  59327. if (this._particle.rotationQuaternion) {
  59328. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59329. }
  59330. else {
  59331. this._yaw = this._particle.rotation.y;
  59332. this._pitch = this._particle.rotation.x;
  59333. this._roll = this._particle.rotation.z;
  59334. this._quaternionRotationYPR();
  59335. }
  59336. this._quaternionToRotationMatrix();
  59337. }
  59338. if (this._particleHasParent) {
  59339. this._parent = this.particles[this._particle.parentId];
  59340. 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];
  59341. 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];
  59342. 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];
  59343. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59344. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59345. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59346. if (this._computeParticleRotation || this.billboard) {
  59347. 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];
  59348. 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];
  59349. 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];
  59350. 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];
  59351. 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];
  59352. 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];
  59353. 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];
  59354. 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];
  59355. 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];
  59356. }
  59357. }
  59358. else {
  59359. this._particle._globalPosition.x = this._particle.position.x;
  59360. this._particle._globalPosition.y = this._particle.position.y;
  59361. this._particle._globalPosition.z = this._particle.position.z;
  59362. if (this._computeParticleRotation || this.billboard) {
  59363. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59364. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59365. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59366. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59367. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59368. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59369. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59370. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59371. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59372. }
  59373. }
  59374. if (this._particle.translateFromPivot) {
  59375. this._pivotBackTranslation.x = 0.0;
  59376. this._pivotBackTranslation.y = 0.0;
  59377. this._pivotBackTranslation.z = 0.0;
  59378. }
  59379. else {
  59380. this._pivotBackTranslation.x = this._scaledPivot.x;
  59381. this._pivotBackTranslation.y = this._scaledPivot.y;
  59382. this._pivotBackTranslation.z = this._scaledPivot.z;
  59383. }
  59384. // particle vertex loop
  59385. for (pt = 0; pt < this._shape.length; pt++) {
  59386. idx = index + pt * 3;
  59387. colidx = colorIndex + pt * 4;
  59388. uvidx = uvIndex + pt * 2;
  59389. this._vertex.x = this._shape[pt].x;
  59390. this._vertex.y = this._shape[pt].y;
  59391. this._vertex.z = this._shape[pt].z;
  59392. if (this._computeParticleVertex) {
  59393. this.updateParticleVertex(this._particle, this._vertex, pt);
  59394. }
  59395. // positions
  59396. this._vertex.x *= this._particle.scaling.x;
  59397. this._vertex.y *= this._particle.scaling.y;
  59398. this._vertex.z *= this._particle.scaling.z;
  59399. this._vertex.x -= this._scaledPivot.x;
  59400. this._vertex.y -= this._scaledPivot.y;
  59401. this._vertex.z -= this._scaledPivot.z;
  59402. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59403. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59404. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59405. this._rotated.x += this._pivotBackTranslation.x;
  59406. this._rotated.y += this._pivotBackTranslation.y;
  59407. this._rotated.z += this._pivotBackTranslation.z;
  59408. 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;
  59409. 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;
  59410. 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;
  59411. if (this._computeBoundingBox) {
  59412. if (this._positions32[idx] < this._minimum.x) {
  59413. this._minimum.x = this._positions32[idx];
  59414. }
  59415. if (this._positions32[idx] > this._maximum.x) {
  59416. this._maximum.x = this._positions32[idx];
  59417. }
  59418. if (this._positions32[idx + 1] < this._minimum.y) {
  59419. this._minimum.y = this._positions32[idx + 1];
  59420. }
  59421. if (this._positions32[idx + 1] > this._maximum.y) {
  59422. this._maximum.y = this._positions32[idx + 1];
  59423. }
  59424. if (this._positions32[idx + 2] < this._minimum.z) {
  59425. this._minimum.z = this._positions32[idx + 2];
  59426. }
  59427. if (this._positions32[idx + 2] > this._maximum.z) {
  59428. this._maximum.z = this._positions32[idx + 2];
  59429. }
  59430. }
  59431. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59432. if (!this._computeParticleVertex) {
  59433. this._normal.x = this._fixedNormal32[idx];
  59434. this._normal.y = this._fixedNormal32[idx + 1];
  59435. this._normal.z = this._fixedNormal32[idx + 2];
  59436. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59437. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59438. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59439. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59440. 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;
  59441. 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;
  59442. }
  59443. if (this._computeParticleColor && this._particle.color) {
  59444. this._colors32[colidx] = this._particle.color.r;
  59445. this._colors32[colidx + 1] = this._particle.color.g;
  59446. this._colors32[colidx + 2] = this._particle.color.b;
  59447. this._colors32[colidx + 3] = this._particle.color.a;
  59448. }
  59449. if (this._computeParticleTexture) {
  59450. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59451. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59452. }
  59453. }
  59454. }
  59455. // particle just set invisible : scaled to zero and positioned at the origin
  59456. else {
  59457. this._particle._stillInvisible = true; // mark the particle as invisible
  59458. for (pt = 0; pt < this._shape.length; pt++) {
  59459. idx = index + pt * 3;
  59460. colidx = colorIndex + pt * 4;
  59461. uvidx = uvIndex + pt * 2;
  59462. this._positions32[idx] = 0.0;
  59463. this._positions32[idx + 1] = 0.0;
  59464. this._positions32[idx + 2] = 0.0;
  59465. this._normals32[idx] = 0.0;
  59466. this._normals32[idx + 1] = 0.0;
  59467. this._normals32[idx + 2] = 0.0;
  59468. if (this._computeParticleColor && this._particle.color) {
  59469. this._colors32[colidx] = this._particle.color.r;
  59470. this._colors32[colidx + 1] = this._particle.color.g;
  59471. this._colors32[colidx + 2] = this._particle.color.b;
  59472. this._colors32[colidx + 3] = this._particle.color.a;
  59473. }
  59474. if (this._computeParticleTexture) {
  59475. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59476. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59477. }
  59478. }
  59479. }
  59480. // if the particle intersections must be computed : update the bbInfo
  59481. if (this._particlesIntersect) {
  59482. var bInfo = this._particle._boundingInfo;
  59483. var bBox = bInfo.boundingBox;
  59484. var bSphere = bInfo.boundingSphere;
  59485. if (!this._bSphereOnly) {
  59486. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59487. for (var b = 0; b < bBox.vectors.length; b++) {
  59488. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59489. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59490. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59491. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59492. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59493. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59494. 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;
  59495. 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;
  59496. 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;
  59497. }
  59498. bBox._update(this.mesh._worldMatrix);
  59499. }
  59500. // place and scale the particle bouding sphere in the SPS local system, then update it
  59501. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59502. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59503. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59504. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59505. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59506. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59507. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59508. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59509. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59510. 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));
  59511. bSphere._update(this.mesh._worldMatrix);
  59512. }
  59513. // increment indexes for the next particle
  59514. index = idx + 3;
  59515. colorIndex = colidx + 4;
  59516. uvIndex = uvidx + 2;
  59517. }
  59518. // if the VBO must be updated
  59519. if (update) {
  59520. if (this._computeParticleColor) {
  59521. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59522. }
  59523. if (this._computeParticleTexture) {
  59524. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59525. }
  59526. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59527. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59528. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59529. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59530. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59531. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59532. for (var i = 0; i < this._normals32.length; i++) {
  59533. this._fixedNormal32[i] = this._normals32[i];
  59534. }
  59535. }
  59536. if (!this.mesh.areNormalsFrozen) {
  59537. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59538. }
  59539. }
  59540. if (this._depthSort && this._depthSortParticles) {
  59541. this.depthSortedParticles.sort(this._depthSortFunction);
  59542. var dspl = this.depthSortedParticles.length;
  59543. var sorted = 0;
  59544. var lind = 0;
  59545. var sind = 0;
  59546. var sid = 0;
  59547. for (sorted = 0; sorted < dspl; sorted++) {
  59548. lind = this.depthSortedParticles[sorted].indicesLength;
  59549. sind = this.depthSortedParticles[sorted].ind;
  59550. for (var i = 0; i < lind; i++) {
  59551. this._indices32[sid] = this._indices[sind + i];
  59552. sid++;
  59553. }
  59554. }
  59555. this.mesh.updateIndices(this._indices32);
  59556. }
  59557. }
  59558. if (this._computeBoundingBox) {
  59559. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59560. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59561. }
  59562. this.afterUpdateParticles(start, end, update);
  59563. return this;
  59564. };
  59565. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59566. this._halfroll = this._roll * 0.5;
  59567. this._halfpitch = this._pitch * 0.5;
  59568. this._halfyaw = this._yaw * 0.5;
  59569. this._sinRoll = Math.sin(this._halfroll);
  59570. this._cosRoll = Math.cos(this._halfroll);
  59571. this._sinPitch = Math.sin(this._halfpitch);
  59572. this._cosPitch = Math.cos(this._halfpitch);
  59573. this._sinYaw = Math.sin(this._halfyaw);
  59574. this._cosYaw = Math.cos(this._halfyaw);
  59575. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59576. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59577. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59578. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59579. };
  59580. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59581. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59582. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59583. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59584. this._rotMatrix.m[3] = 0;
  59585. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59586. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59587. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59588. this._rotMatrix.m[7] = 0;
  59589. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59590. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59591. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59592. this._rotMatrix.m[11] = 0;
  59593. this._rotMatrix.m[12] = 0;
  59594. this._rotMatrix.m[13] = 0;
  59595. this._rotMatrix.m[14] = 0;
  59596. this._rotMatrix.m[15] = 1.0;
  59597. };
  59598. /**
  59599. * Disposes the SPS.
  59600. */
  59601. SolidParticleSystem.prototype.dispose = function () {
  59602. this.mesh.dispose();
  59603. this.vars = null;
  59604. // drop references to internal big arrays for the GC
  59605. this._positions = null;
  59606. this._indices = null;
  59607. this._normals = null;
  59608. this._uvs = null;
  59609. this._colors = null;
  59610. this._indices32 = null;
  59611. this._positions32 = null;
  59612. this._normals32 = null;
  59613. this._fixedNormal32 = null;
  59614. this._uvs32 = null;
  59615. this._colors32 = null;
  59616. this.pickedParticles = null;
  59617. };
  59618. /**
  59619. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59620. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59621. * @returns the SPS.
  59622. */
  59623. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59624. if (!this._isVisibilityBoxLocked) {
  59625. this.mesh.refreshBoundingInfo();
  59626. }
  59627. return this;
  59628. };
  59629. /**
  59630. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59631. * @param size the size (float) of the visibility box
  59632. * note : this doesn't lock the SPS mesh bounding box.
  59633. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59634. */
  59635. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59636. var vis = size / 2;
  59637. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59638. };
  59639. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59640. /**
  59641. * Gets whether the SPS as always visible or not
  59642. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59643. */
  59644. get: function () {
  59645. return this._alwaysVisible;
  59646. },
  59647. /**
  59648. * Sets the SPS as always visible or not
  59649. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59650. */
  59651. set: function (val) {
  59652. this._alwaysVisible = val;
  59653. this.mesh.alwaysSelectAsActiveMesh = val;
  59654. },
  59655. enumerable: true,
  59656. configurable: true
  59657. });
  59658. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59659. /**
  59660. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59661. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59662. */
  59663. get: function () {
  59664. return this._isVisibilityBoxLocked;
  59665. },
  59666. /**
  59667. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59668. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59669. */
  59670. set: function (val) {
  59671. this._isVisibilityBoxLocked = val;
  59672. var boundingInfo = this.mesh.getBoundingInfo();
  59673. boundingInfo.isLocked = val;
  59674. },
  59675. enumerable: true,
  59676. configurable: true
  59677. });
  59678. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59679. /**
  59680. * Gets if `setParticles()` computes the particle rotations or not.
  59681. * Default value : true. The SPS is faster when it's set to false.
  59682. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59683. */
  59684. get: function () {
  59685. return this._computeParticleRotation;
  59686. },
  59687. /**
  59688. * Tells to `setParticles()` to compute the particle rotations or not.
  59689. * Default value : true. The SPS is faster when it's set to false.
  59690. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59691. */
  59692. set: function (val) {
  59693. this._computeParticleRotation = val;
  59694. },
  59695. enumerable: true,
  59696. configurable: true
  59697. });
  59698. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59699. /**
  59700. * Gets if `setParticles()` computes the particle colors or not.
  59701. * Default value : true. The SPS is faster when it's set to false.
  59702. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59703. */
  59704. get: function () {
  59705. return this._computeParticleColor;
  59706. },
  59707. /**
  59708. * Tells to `setParticles()` to compute the particle colors or not.
  59709. * Default value : true. The SPS is faster when it's set to false.
  59710. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59711. */
  59712. set: function (val) {
  59713. this._computeParticleColor = val;
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59719. /**
  59720. * Gets if `setParticles()` computes the particle textures or not.
  59721. * Default value : true. The SPS is faster when it's set to false.
  59722. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59723. */
  59724. get: function () {
  59725. return this._computeParticleTexture;
  59726. },
  59727. set: function (val) {
  59728. this._computeParticleTexture = val;
  59729. },
  59730. enumerable: true,
  59731. configurable: true
  59732. });
  59733. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59734. /**
  59735. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59736. * Default value : false. The SPS is faster when it's set to false.
  59737. * Note : the particle custom vertex positions aren't stored values.
  59738. */
  59739. get: function () {
  59740. return this._computeParticleVertex;
  59741. },
  59742. /**
  59743. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59744. * Default value : false. The SPS is faster when it's set to false.
  59745. * Note : the particle custom vertex positions aren't stored values.
  59746. */
  59747. set: function (val) {
  59748. this._computeParticleVertex = val;
  59749. },
  59750. enumerable: true,
  59751. configurable: true
  59752. });
  59753. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59754. /**
  59755. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59756. */
  59757. get: function () {
  59758. return this._computeBoundingBox;
  59759. },
  59760. /**
  59761. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59762. */
  59763. set: function (val) {
  59764. this._computeBoundingBox = val;
  59765. },
  59766. enumerable: true,
  59767. configurable: true
  59768. });
  59769. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59770. /**
  59771. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59772. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59773. * Default : `true`
  59774. */
  59775. get: function () {
  59776. return this._depthSortParticles;
  59777. },
  59778. /**
  59779. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59780. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59781. * Default : `true`
  59782. */
  59783. set: function (val) {
  59784. this._depthSortParticles = val;
  59785. },
  59786. enumerable: true,
  59787. configurable: true
  59788. });
  59789. // =======================================================================
  59790. // Particle behavior logic
  59791. // these following methods may be overwritten by the user to fit his needs
  59792. /**
  59793. * This function does nothing. It may be overwritten to set all the particle first values.
  59794. * The SPS doesn't call this function, you may have to call it by your own.
  59795. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59796. */
  59797. SolidParticleSystem.prototype.initParticles = function () {
  59798. };
  59799. /**
  59800. * This function does nothing. It may be overwritten to recycle a particle.
  59801. * The SPS doesn't call this function, you may have to call it by your own.
  59802. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59803. * @param particle The particle to recycle
  59804. * @returns the recycled particle
  59805. */
  59806. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59807. return particle;
  59808. };
  59809. /**
  59810. * Updates a particle : this function should be overwritten by the user.
  59811. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59812. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59813. * @example : just set a particle position or velocity and recycle conditions
  59814. * @param particle The particle to update
  59815. * @returns the updated particle
  59816. */
  59817. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59818. return particle;
  59819. };
  59820. /**
  59821. * Updates a vertex of a particle : it can be overwritten by the user.
  59822. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59823. * @param particle the current particle
  59824. * @param vertex the current index of the current particle
  59825. * @param pt the index of the current vertex in the particle shape
  59826. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59827. * @example : just set a vertex particle position
  59828. * @returns the updated vertex
  59829. */
  59830. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59831. return vertex;
  59832. };
  59833. /**
  59834. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59835. * This does nothing and may be overwritten by the user.
  59836. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59837. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59838. * @param update the boolean update value actually passed to setParticles()
  59839. */
  59840. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59841. };
  59842. /**
  59843. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59844. * This will be passed three parameters.
  59845. * This does nothing and may be overwritten by the user.
  59846. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59847. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59848. * @param update the boolean update value actually passed to setParticles()
  59849. */
  59850. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59851. };
  59852. return SolidParticleSystem;
  59853. }());
  59854. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59855. })(BABYLON || (BABYLON = {}));
  59856. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59857. var BABYLON;
  59858. (function (BABYLON) {
  59859. var ShaderMaterial = /** @class */ (function (_super) {
  59860. __extends(ShaderMaterial, _super);
  59861. function ShaderMaterial(name, scene, shaderPath, options) {
  59862. var _this = _super.call(this, name, scene) || this;
  59863. _this._textures = {};
  59864. _this._textureArrays = {};
  59865. _this._floats = {};
  59866. _this._ints = {};
  59867. _this._floatsArrays = {};
  59868. _this._colors3 = {};
  59869. _this._colors3Arrays = {};
  59870. _this._colors4 = {};
  59871. _this._vectors2 = {};
  59872. _this._vectors3 = {};
  59873. _this._vectors4 = {};
  59874. _this._matrices = {};
  59875. _this._matrices3x3 = {};
  59876. _this._matrices2x2 = {};
  59877. _this._vectors2Arrays = {};
  59878. _this._vectors3Arrays = {};
  59879. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59880. _this._shaderPath = shaderPath;
  59881. options.needAlphaBlending = options.needAlphaBlending || false;
  59882. options.needAlphaTesting = options.needAlphaTesting || false;
  59883. options.attributes = options.attributes || ["position", "normal", "uv"];
  59884. options.uniforms = options.uniforms || ["worldViewProjection"];
  59885. options.uniformBuffers = options.uniformBuffers || [];
  59886. options.samplers = options.samplers || [];
  59887. options.defines = options.defines || [];
  59888. _this._options = options;
  59889. return _this;
  59890. }
  59891. ShaderMaterial.prototype.getClassName = function () {
  59892. return "ShaderMaterial";
  59893. };
  59894. ShaderMaterial.prototype.needAlphaBlending = function () {
  59895. return this._options.needAlphaBlending;
  59896. };
  59897. ShaderMaterial.prototype.needAlphaTesting = function () {
  59898. return this._options.needAlphaTesting;
  59899. };
  59900. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59901. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59902. this._options.uniforms.push(uniformName);
  59903. }
  59904. };
  59905. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59906. if (this._options.samplers.indexOf(name) === -1) {
  59907. this._options.samplers.push(name);
  59908. }
  59909. this._textures[name] = texture;
  59910. return this;
  59911. };
  59912. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59913. if (this._options.samplers.indexOf(name) === -1) {
  59914. this._options.samplers.push(name);
  59915. }
  59916. this._checkUniform(name);
  59917. this._textureArrays[name] = textures;
  59918. return this;
  59919. };
  59920. ShaderMaterial.prototype.setFloat = function (name, value) {
  59921. this._checkUniform(name);
  59922. this._floats[name] = value;
  59923. return this;
  59924. };
  59925. ShaderMaterial.prototype.setInt = function (name, value) {
  59926. this._checkUniform(name);
  59927. this._ints[name] = value;
  59928. return this;
  59929. };
  59930. ShaderMaterial.prototype.setFloats = function (name, value) {
  59931. this._checkUniform(name);
  59932. this._floatsArrays[name] = value;
  59933. return this;
  59934. };
  59935. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59936. this._checkUniform(name);
  59937. this._colors3[name] = value;
  59938. return this;
  59939. };
  59940. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59941. this._checkUniform(name);
  59942. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59943. color.toArray(arr, arr.length);
  59944. return arr;
  59945. }, []);
  59946. return this;
  59947. };
  59948. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59949. this._checkUniform(name);
  59950. this._colors4[name] = value;
  59951. return this;
  59952. };
  59953. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59954. this._checkUniform(name);
  59955. this._vectors2[name] = value;
  59956. return this;
  59957. };
  59958. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59959. this._checkUniform(name);
  59960. this._vectors3[name] = value;
  59961. return this;
  59962. };
  59963. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59964. this._checkUniform(name);
  59965. this._vectors4[name] = value;
  59966. return this;
  59967. };
  59968. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59969. this._checkUniform(name);
  59970. this._matrices[name] = value;
  59971. return this;
  59972. };
  59973. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59974. this._checkUniform(name);
  59975. this._matrices3x3[name] = value;
  59976. return this;
  59977. };
  59978. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59979. this._checkUniform(name);
  59980. this._matrices2x2[name] = value;
  59981. return this;
  59982. };
  59983. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59984. this._checkUniform(name);
  59985. this._vectors2Arrays[name] = value;
  59986. return this;
  59987. };
  59988. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59989. this._checkUniform(name);
  59990. this._vectors3Arrays[name] = value;
  59991. return this;
  59992. };
  59993. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59994. if (!mesh) {
  59995. return true;
  59996. }
  59997. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59998. return false;
  59999. }
  60000. return false;
  60001. };
  60002. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60003. var scene = this.getScene();
  60004. var engine = scene.getEngine();
  60005. if (!this.checkReadyOnEveryCall) {
  60006. if (this._renderId === scene.getRenderId()) {
  60007. if (this._checkCache(scene, mesh, useInstances)) {
  60008. return true;
  60009. }
  60010. }
  60011. }
  60012. // Instances
  60013. var defines = [];
  60014. var attribs = [];
  60015. var fallbacks = new BABYLON.EffectFallbacks();
  60016. if (useInstances) {
  60017. defines.push("#define INSTANCES");
  60018. }
  60019. for (var index = 0; index < this._options.defines.length; index++) {
  60020. defines.push(this._options.defines[index]);
  60021. }
  60022. for (var index = 0; index < this._options.attributes.length; index++) {
  60023. attribs.push(this._options.attributes[index]);
  60024. }
  60025. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60026. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60027. defines.push("#define VERTEXCOLOR");
  60028. }
  60029. // Bones
  60030. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60031. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60032. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60033. if (mesh.numBoneInfluencers > 4) {
  60034. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60035. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60036. }
  60037. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60038. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60039. fallbacks.addCPUSkinningFallback(0, mesh);
  60040. if (this._options.uniforms.indexOf("mBones") === -1) {
  60041. this._options.uniforms.push("mBones");
  60042. }
  60043. }
  60044. else {
  60045. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60046. }
  60047. // Textures
  60048. for (var name in this._textures) {
  60049. if (!this._textures[name].isReady()) {
  60050. return false;
  60051. }
  60052. }
  60053. // Alpha test
  60054. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60055. defines.push("#define ALPHATEST");
  60056. }
  60057. var previousEffect = this._effect;
  60058. var join = defines.join("\n");
  60059. this._effect = engine.createEffect(this._shaderPath, {
  60060. attributes: attribs,
  60061. uniformsNames: this._options.uniforms,
  60062. uniformBuffersNames: this._options.uniformBuffers,
  60063. samplers: this._options.samplers,
  60064. defines: join,
  60065. fallbacks: fallbacks,
  60066. onCompiled: this.onCompiled,
  60067. onError: this.onError
  60068. }, engine);
  60069. if (!this._effect.isReady()) {
  60070. return false;
  60071. }
  60072. if (previousEffect !== this._effect) {
  60073. scene.resetCachedMaterial();
  60074. }
  60075. this._renderId = scene.getRenderId();
  60076. return true;
  60077. };
  60078. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60079. var scene = this.getScene();
  60080. if (!this._effect) {
  60081. return;
  60082. }
  60083. if (this._options.uniforms.indexOf("world") !== -1) {
  60084. this._effect.setMatrix("world", world);
  60085. }
  60086. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60087. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60088. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60089. }
  60090. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60091. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60092. }
  60093. };
  60094. ShaderMaterial.prototype.bind = function (world, mesh) {
  60095. // Std values
  60096. this.bindOnlyWorldMatrix(world);
  60097. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60098. if (this._options.uniforms.indexOf("view") !== -1) {
  60099. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60100. }
  60101. if (this._options.uniforms.indexOf("projection") !== -1) {
  60102. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60103. }
  60104. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60105. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60106. }
  60107. // Bones
  60108. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60109. var name;
  60110. // Texture
  60111. for (name in this._textures) {
  60112. this._effect.setTexture(name, this._textures[name]);
  60113. }
  60114. // Texture arrays
  60115. for (name in this._textureArrays) {
  60116. this._effect.setTextureArray(name, this._textureArrays[name]);
  60117. }
  60118. // Int
  60119. for (name in this._ints) {
  60120. this._effect.setInt(name, this._ints[name]);
  60121. }
  60122. // Float
  60123. for (name in this._floats) {
  60124. this._effect.setFloat(name, this._floats[name]);
  60125. }
  60126. // Floats
  60127. for (name in this._floatsArrays) {
  60128. this._effect.setArray(name, this._floatsArrays[name]);
  60129. }
  60130. // Color3
  60131. for (name in this._colors3) {
  60132. this._effect.setColor3(name, this._colors3[name]);
  60133. }
  60134. for (name in this._colors3Arrays) {
  60135. this._effect.setArray3(name, this._colors3Arrays[name]);
  60136. }
  60137. // Color4
  60138. for (name in this._colors4) {
  60139. var color = this._colors4[name];
  60140. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60141. }
  60142. // Vector2
  60143. for (name in this._vectors2) {
  60144. this._effect.setVector2(name, this._vectors2[name]);
  60145. }
  60146. // Vector3
  60147. for (name in this._vectors3) {
  60148. this._effect.setVector3(name, this._vectors3[name]);
  60149. }
  60150. // Vector4
  60151. for (name in this._vectors4) {
  60152. this._effect.setVector4(name, this._vectors4[name]);
  60153. }
  60154. // Matrix
  60155. for (name in this._matrices) {
  60156. this._effect.setMatrix(name, this._matrices[name]);
  60157. }
  60158. // Matrix 3x3
  60159. for (name in this._matrices3x3) {
  60160. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60161. }
  60162. // Matrix 2x2
  60163. for (name in this._matrices2x2) {
  60164. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60165. }
  60166. // Vector2Array
  60167. for (name in this._vectors2Arrays) {
  60168. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60169. }
  60170. // Vector3Array
  60171. for (name in this._vectors3Arrays) {
  60172. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60173. }
  60174. }
  60175. this._afterBind(mesh);
  60176. };
  60177. ShaderMaterial.prototype.getActiveTextures = function () {
  60178. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60179. for (var name in this._textures) {
  60180. activeTextures.push(this._textures[name]);
  60181. }
  60182. for (var name in this._textureArrays) {
  60183. var array = this._textureArrays[name];
  60184. for (var index = 0; index < array.length; index++) {
  60185. activeTextures.push(array[index]);
  60186. }
  60187. }
  60188. return activeTextures;
  60189. };
  60190. ShaderMaterial.prototype.hasTexture = function (texture) {
  60191. if (_super.prototype.hasTexture.call(this, texture)) {
  60192. return true;
  60193. }
  60194. for (var name in this._textures) {
  60195. if (this._textures[name] === texture) {
  60196. return true;
  60197. }
  60198. }
  60199. for (var name in this._textureArrays) {
  60200. var array = this._textureArrays[name];
  60201. for (var index = 0; index < array.length; index++) {
  60202. if (array[index] === texture) {
  60203. return true;
  60204. }
  60205. }
  60206. }
  60207. return false;
  60208. };
  60209. ShaderMaterial.prototype.clone = function (name) {
  60210. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60211. return newShaderMaterial;
  60212. };
  60213. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60214. if (forceDisposeTextures) {
  60215. var name;
  60216. for (name in this._textures) {
  60217. this._textures[name].dispose();
  60218. }
  60219. for (name in this._textureArrays) {
  60220. var array = this._textureArrays[name];
  60221. for (var index = 0; index < array.length; index++) {
  60222. array[index].dispose();
  60223. }
  60224. }
  60225. }
  60226. this._textures = {};
  60227. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60228. };
  60229. ShaderMaterial.prototype.serialize = function () {
  60230. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60231. serializationObject.customType = "BABYLON.ShaderMaterial";
  60232. serializationObject.options = this._options;
  60233. serializationObject.shaderPath = this._shaderPath;
  60234. var name;
  60235. // Texture
  60236. serializationObject.textures = {};
  60237. for (name in this._textures) {
  60238. serializationObject.textures[name] = this._textures[name].serialize();
  60239. }
  60240. // Texture arrays
  60241. serializationObject.textureArrays = {};
  60242. for (name in this._textureArrays) {
  60243. serializationObject.textureArrays[name] = [];
  60244. var array = this._textureArrays[name];
  60245. for (var index = 0; index < array.length; index++) {
  60246. serializationObject.textureArrays[name].push(array[index].serialize());
  60247. }
  60248. }
  60249. // Float
  60250. serializationObject.floats = {};
  60251. for (name in this._floats) {
  60252. serializationObject.floats[name] = this._floats[name];
  60253. }
  60254. // Float s
  60255. serializationObject.FloatArrays = {};
  60256. for (name in this._floatsArrays) {
  60257. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60258. }
  60259. // Color3
  60260. serializationObject.colors3 = {};
  60261. for (name in this._colors3) {
  60262. serializationObject.colors3[name] = this._colors3[name].asArray();
  60263. }
  60264. // Color3 array
  60265. serializationObject.colors3Arrays = {};
  60266. for (name in this._colors3Arrays) {
  60267. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60268. }
  60269. // Color4
  60270. serializationObject.colors4 = {};
  60271. for (name in this._colors4) {
  60272. serializationObject.colors4[name] = this._colors4[name].asArray();
  60273. }
  60274. // Vector2
  60275. serializationObject.vectors2 = {};
  60276. for (name in this._vectors2) {
  60277. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60278. }
  60279. // Vector3
  60280. serializationObject.vectors3 = {};
  60281. for (name in this._vectors3) {
  60282. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60283. }
  60284. // Vector4
  60285. serializationObject.vectors4 = {};
  60286. for (name in this._vectors4) {
  60287. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60288. }
  60289. // Matrix
  60290. serializationObject.matrices = {};
  60291. for (name in this._matrices) {
  60292. serializationObject.matrices[name] = this._matrices[name].asArray();
  60293. }
  60294. // Matrix 3x3
  60295. serializationObject.matrices3x3 = {};
  60296. for (name in this._matrices3x3) {
  60297. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60298. }
  60299. // Matrix 2x2
  60300. serializationObject.matrices2x2 = {};
  60301. for (name in this._matrices2x2) {
  60302. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60303. }
  60304. // Vector2Array
  60305. serializationObject.vectors2Arrays = {};
  60306. for (name in this._vectors2Arrays) {
  60307. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60308. }
  60309. // Vector3Array
  60310. serializationObject.vectors3Arrays = {};
  60311. for (name in this._vectors3Arrays) {
  60312. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60313. }
  60314. return serializationObject;
  60315. };
  60316. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60317. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60318. var name;
  60319. // Texture
  60320. for (name in source.textures) {
  60321. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60322. }
  60323. // Texture arrays
  60324. for (name in source.textureArrays) {
  60325. var array = source.textureArrays[name];
  60326. var textureArray = new Array();
  60327. for (var index = 0; index < array.length; index++) {
  60328. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60329. }
  60330. material.setTextureArray(name, textureArray);
  60331. }
  60332. // Float
  60333. for (name in source.floats) {
  60334. material.setFloat(name, source.floats[name]);
  60335. }
  60336. // Float s
  60337. for (name in source.floatsArrays) {
  60338. material.setFloats(name, source.floatsArrays[name]);
  60339. }
  60340. // Color3
  60341. for (name in source.colors3) {
  60342. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60343. }
  60344. // Color3 arrays
  60345. for (name in source.colors3Arrays) {
  60346. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60347. if (i % 3 === 0) {
  60348. arr.push([num]);
  60349. }
  60350. else {
  60351. arr[arr.length - 1].push(num);
  60352. }
  60353. return arr;
  60354. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60355. material.setColor3Array(name, colors);
  60356. }
  60357. // Color4
  60358. for (name in source.colors4) {
  60359. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60360. }
  60361. // Vector2
  60362. for (name in source.vectors2) {
  60363. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60364. }
  60365. // Vector3
  60366. for (name in source.vectors3) {
  60367. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60368. }
  60369. // Vector4
  60370. for (name in source.vectors4) {
  60371. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60372. }
  60373. // Matrix
  60374. for (name in source.matrices) {
  60375. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60376. }
  60377. // Matrix 3x3
  60378. for (name in source.matrices3x3) {
  60379. material.setMatrix3x3(name, source.matrices3x3[name]);
  60380. }
  60381. // Matrix 2x2
  60382. for (name in source.matrices2x2) {
  60383. material.setMatrix2x2(name, source.matrices2x2[name]);
  60384. }
  60385. // Vector2Array
  60386. for (name in source.vectors2Arrays) {
  60387. material.setArray2(name, source.vectors2Arrays[name]);
  60388. }
  60389. // Vector3Array
  60390. for (name in source.vectors3Arrays) {
  60391. material.setArray3(name, source.vectors3Arrays[name]);
  60392. }
  60393. return material;
  60394. };
  60395. return ShaderMaterial;
  60396. }(BABYLON.Material));
  60397. BABYLON.ShaderMaterial = ShaderMaterial;
  60398. })(BABYLON || (BABYLON = {}));
  60399. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60400. var BABYLON;
  60401. (function (BABYLON) {
  60402. var GroundMesh = /** @class */ (function (_super) {
  60403. __extends(GroundMesh, _super);
  60404. function GroundMesh(name, scene) {
  60405. var _this = _super.call(this, name, scene) || this;
  60406. _this.generateOctree = false;
  60407. return _this;
  60408. }
  60409. GroundMesh.prototype.getClassName = function () {
  60410. return "GroundMesh";
  60411. };
  60412. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60413. get: function () {
  60414. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60415. },
  60416. enumerable: true,
  60417. configurable: true
  60418. });
  60419. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60420. get: function () {
  60421. return this._subdivisionsX;
  60422. },
  60423. enumerable: true,
  60424. configurable: true
  60425. });
  60426. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60427. get: function () {
  60428. return this._subdivisionsY;
  60429. },
  60430. enumerable: true,
  60431. configurable: true
  60432. });
  60433. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60434. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60435. this._subdivisionsX = chunksCount;
  60436. this._subdivisionsY = chunksCount;
  60437. this.subdivide(chunksCount);
  60438. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60439. };
  60440. /**
  60441. * Returns a height (y) value in the Worl system :
  60442. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60443. * Returns the ground y position if (x, z) are outside the ground surface.
  60444. */
  60445. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60446. var world = this.getWorldMatrix();
  60447. var invMat = BABYLON.Tmp.Matrix[5];
  60448. world.invertToRef(invMat);
  60449. var tmpVect = BABYLON.Tmp.Vector3[8];
  60450. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60451. x = tmpVect.x;
  60452. z = tmpVect.z;
  60453. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60454. return this.position.y;
  60455. }
  60456. if (!this._heightQuads || this._heightQuads.length == 0) {
  60457. this._initHeightQuads();
  60458. this._computeHeightQuads();
  60459. }
  60460. var facet = this._getFacetAt(x, z);
  60461. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60462. // return y in the World system
  60463. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60464. return tmpVect.y;
  60465. };
  60466. /**
  60467. * Returns a normalized vector (Vector3) orthogonal to the ground
  60468. * at the ground coordinates (x, z) expressed in the World system.
  60469. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60470. */
  60471. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60472. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60473. this.getNormalAtCoordinatesToRef(x, z, normal);
  60474. return normal;
  60475. };
  60476. /**
  60477. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60478. * at the ground coordinates (x, z) expressed in the World system.
  60479. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60480. * Returns the GroundMesh.
  60481. */
  60482. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60483. var world = this.getWorldMatrix();
  60484. var tmpMat = BABYLON.Tmp.Matrix[5];
  60485. world.invertToRef(tmpMat);
  60486. var tmpVect = BABYLON.Tmp.Vector3[8];
  60487. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60488. x = tmpVect.x;
  60489. z = tmpVect.z;
  60490. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60491. return this;
  60492. }
  60493. if (!this._heightQuads || this._heightQuads.length == 0) {
  60494. this._initHeightQuads();
  60495. this._computeHeightQuads();
  60496. }
  60497. var facet = this._getFacetAt(x, z);
  60498. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60499. return this;
  60500. };
  60501. /**
  60502. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60503. * if the ground has been updated.
  60504. * This can be used in the render loop.
  60505. * Returns the GroundMesh.
  60506. */
  60507. GroundMesh.prototype.updateCoordinateHeights = function () {
  60508. if (!this._heightQuads || this._heightQuads.length == 0) {
  60509. this._initHeightQuads();
  60510. }
  60511. this._computeHeightQuads();
  60512. return this;
  60513. };
  60514. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60515. GroundMesh.prototype._getFacetAt = function (x, z) {
  60516. // retrieve col and row from x, z coordinates in the ground local system
  60517. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60518. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60519. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60520. var facet;
  60521. if (z < quad.slope.x * x + quad.slope.y) {
  60522. facet = quad.facet1;
  60523. }
  60524. else {
  60525. facet = quad.facet2;
  60526. }
  60527. return facet;
  60528. };
  60529. // Creates and populates the heightMap array with "facet" elements :
  60530. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60531. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60532. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60533. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60534. // Returns the GroundMesh.
  60535. GroundMesh.prototype._initHeightQuads = function () {
  60536. var subdivisionsX = this._subdivisionsX;
  60537. var subdivisionsY = this._subdivisionsY;
  60538. this._heightQuads = new Array();
  60539. for (var row = 0; row < subdivisionsY; row++) {
  60540. for (var col = 0; col < subdivisionsX; col++) {
  60541. 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) };
  60542. this._heightQuads[row * subdivisionsX + col] = quad;
  60543. }
  60544. }
  60545. return this;
  60546. };
  60547. // Compute each quad element values and update the the heightMap array :
  60548. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60549. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60550. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60551. // Returns the GroundMesh.
  60552. GroundMesh.prototype._computeHeightQuads = function () {
  60553. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60554. if (!positions) {
  60555. return this;
  60556. }
  60557. var v1 = BABYLON.Tmp.Vector3[3];
  60558. var v2 = BABYLON.Tmp.Vector3[2];
  60559. var v3 = BABYLON.Tmp.Vector3[1];
  60560. var v4 = BABYLON.Tmp.Vector3[0];
  60561. var v1v2 = BABYLON.Tmp.Vector3[4];
  60562. var v1v3 = BABYLON.Tmp.Vector3[5];
  60563. var v1v4 = BABYLON.Tmp.Vector3[6];
  60564. var norm1 = BABYLON.Tmp.Vector3[7];
  60565. var norm2 = BABYLON.Tmp.Vector3[8];
  60566. var i = 0;
  60567. var j = 0;
  60568. var k = 0;
  60569. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60570. var h = 0;
  60571. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60572. var d2 = 0;
  60573. var subdivisionsX = this._subdivisionsX;
  60574. var subdivisionsY = this._subdivisionsY;
  60575. for (var row = 0; row < subdivisionsY; row++) {
  60576. for (var col = 0; col < subdivisionsX; col++) {
  60577. i = col * 3;
  60578. j = row * (subdivisionsX + 1) * 3;
  60579. k = (row + 1) * (subdivisionsX + 1) * 3;
  60580. v1.x = positions[j + i];
  60581. v1.y = positions[j + i + 1];
  60582. v1.z = positions[j + i + 2];
  60583. v2.x = positions[j + i + 3];
  60584. v2.y = positions[j + i + 4];
  60585. v2.z = positions[j + i + 5];
  60586. v3.x = positions[k + i];
  60587. v3.y = positions[k + i + 1];
  60588. v3.z = positions[k + i + 2];
  60589. v4.x = positions[k + i + 3];
  60590. v4.y = positions[k + i + 4];
  60591. v4.z = positions[k + i + 5];
  60592. // 2D slope V1V4
  60593. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60594. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60595. // facet equations :
  60596. // we compute each facet normal vector
  60597. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60598. // we compute the value d by applying the equation to v1 which belongs to the plane
  60599. // then we store the facet equation in a Vector4
  60600. v2.subtractToRef(v1, v1v2);
  60601. v3.subtractToRef(v1, v1v3);
  60602. v4.subtractToRef(v1, v1v4);
  60603. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60604. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60605. norm1.normalize();
  60606. norm2.normalize();
  60607. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60608. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60609. var quad = this._heightQuads[row * subdivisionsX + col];
  60610. quad.slope.copyFromFloats(cd, h);
  60611. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60612. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60613. }
  60614. }
  60615. return this;
  60616. };
  60617. GroundMesh.prototype.serialize = function (serializationObject) {
  60618. _super.prototype.serialize.call(this, serializationObject);
  60619. serializationObject.subdivisionsX = this._subdivisionsX;
  60620. serializationObject.subdivisionsY = this._subdivisionsY;
  60621. serializationObject.minX = this._minX;
  60622. serializationObject.maxX = this._maxX;
  60623. serializationObject.minZ = this._minZ;
  60624. serializationObject.maxZ = this._maxZ;
  60625. serializationObject.width = this._width;
  60626. serializationObject.height = this._height;
  60627. };
  60628. GroundMesh.Parse = function (parsedMesh, scene) {
  60629. var result = new GroundMesh(parsedMesh.name, scene);
  60630. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60631. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60632. result._minX = parsedMesh.minX;
  60633. result._maxX = parsedMesh.maxX;
  60634. result._minZ = parsedMesh.minZ;
  60635. result._maxZ = parsedMesh.maxZ;
  60636. result._width = parsedMesh.width;
  60637. result._height = parsedMesh.height;
  60638. return result;
  60639. };
  60640. return GroundMesh;
  60641. }(BABYLON.Mesh));
  60642. BABYLON.GroundMesh = GroundMesh;
  60643. })(BABYLON || (BABYLON = {}));
  60644. //# sourceMappingURL=babylon.groundMesh.js.map
  60645. var BABYLON;
  60646. (function (BABYLON) {
  60647. /**
  60648. * Creates an instance based on a source mesh.
  60649. */
  60650. var InstancedMesh = /** @class */ (function (_super) {
  60651. __extends(InstancedMesh, _super);
  60652. function InstancedMesh(name, source) {
  60653. var _this = _super.call(this, name, source.getScene()) || this;
  60654. source.instances.push(_this);
  60655. _this._sourceMesh = source;
  60656. _this.position.copyFrom(source.position);
  60657. _this.rotation.copyFrom(source.rotation);
  60658. _this.scaling.copyFrom(source.scaling);
  60659. if (source.rotationQuaternion) {
  60660. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60661. }
  60662. _this.infiniteDistance = source.infiniteDistance;
  60663. _this.setPivotMatrix(source.getPivotMatrix());
  60664. _this.refreshBoundingInfo();
  60665. _this._syncSubMeshes();
  60666. return _this;
  60667. }
  60668. /**
  60669. * Returns the string "InstancedMesh".
  60670. */
  60671. InstancedMesh.prototype.getClassName = function () {
  60672. return "InstancedMesh";
  60673. };
  60674. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60675. // Methods
  60676. get: function () {
  60677. return this._sourceMesh.receiveShadows;
  60678. },
  60679. enumerable: true,
  60680. configurable: true
  60681. });
  60682. Object.defineProperty(InstancedMesh.prototype, "material", {
  60683. get: function () {
  60684. return this._sourceMesh.material;
  60685. },
  60686. enumerable: true,
  60687. configurable: true
  60688. });
  60689. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60690. get: function () {
  60691. return this._sourceMesh.visibility;
  60692. },
  60693. enumerable: true,
  60694. configurable: true
  60695. });
  60696. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60697. get: function () {
  60698. return this._sourceMesh.skeleton;
  60699. },
  60700. enumerable: true,
  60701. configurable: true
  60702. });
  60703. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60704. get: function () {
  60705. return this._sourceMesh.renderingGroupId;
  60706. },
  60707. set: function (value) {
  60708. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60709. return;
  60710. }
  60711. //no-op with warning
  60712. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60713. },
  60714. enumerable: true,
  60715. configurable: true
  60716. });
  60717. /**
  60718. * Returns the total number of vertices (integer).
  60719. */
  60720. InstancedMesh.prototype.getTotalVertices = function () {
  60721. return this._sourceMesh.getTotalVertices();
  60722. };
  60723. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60724. get: function () {
  60725. return this._sourceMesh;
  60726. },
  60727. enumerable: true,
  60728. configurable: true
  60729. });
  60730. /**
  60731. * Is this node ready to be used/rendered
  60732. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60733. * @return {boolean} is it ready
  60734. */
  60735. InstancedMesh.prototype.isReady = function (completeCheck) {
  60736. if (completeCheck === void 0) { completeCheck = false; }
  60737. return this._sourceMesh.isReady(completeCheck, true);
  60738. };
  60739. /**
  60740. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60741. */
  60742. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60743. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60744. };
  60745. /**
  60746. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60747. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60748. * The `data` are either a numeric array either a Float32Array.
  60749. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60750. * 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).
  60751. * Note that a new underlying VertexBuffer object is created each call.
  60752. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60753. *
  60754. * Possible `kind` values :
  60755. * - BABYLON.VertexBuffer.PositionKind
  60756. * - BABYLON.VertexBuffer.UVKind
  60757. * - BABYLON.VertexBuffer.UV2Kind
  60758. * - BABYLON.VertexBuffer.UV3Kind
  60759. * - BABYLON.VertexBuffer.UV4Kind
  60760. * - BABYLON.VertexBuffer.UV5Kind
  60761. * - BABYLON.VertexBuffer.UV6Kind
  60762. * - BABYLON.VertexBuffer.ColorKind
  60763. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60764. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60765. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60766. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60767. *
  60768. * Returns the Mesh.
  60769. */
  60770. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60771. if (this.sourceMesh) {
  60772. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60773. }
  60774. return this.sourceMesh;
  60775. };
  60776. /**
  60777. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60778. * If the mesh has no geometry, it is simply returned as it is.
  60779. * The `data` are either a numeric array either a Float32Array.
  60780. * No new underlying VertexBuffer object is created.
  60781. * 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.
  60782. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60783. *
  60784. * Possible `kind` values :
  60785. * - BABYLON.VertexBuffer.PositionKind
  60786. * - BABYLON.VertexBuffer.UVKind
  60787. * - BABYLON.VertexBuffer.UV2Kind
  60788. * - BABYLON.VertexBuffer.UV3Kind
  60789. * - BABYLON.VertexBuffer.UV4Kind
  60790. * - BABYLON.VertexBuffer.UV5Kind
  60791. * - BABYLON.VertexBuffer.UV6Kind
  60792. * - BABYLON.VertexBuffer.ColorKind
  60793. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60794. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60795. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60796. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60797. *
  60798. * Returns the Mesh.
  60799. */
  60800. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60801. if (this.sourceMesh) {
  60802. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60803. }
  60804. return this.sourceMesh;
  60805. };
  60806. /**
  60807. * Sets the mesh indices.
  60808. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60809. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60810. * This method creates a new index buffer each call.
  60811. * Returns the Mesh.
  60812. */
  60813. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60814. if (totalVertices === void 0) { totalVertices = null; }
  60815. if (this.sourceMesh) {
  60816. this.sourceMesh.setIndices(indices, totalVertices);
  60817. }
  60818. return this.sourceMesh;
  60819. };
  60820. /**
  60821. * Boolean : True if the mesh owns the requested kind of data.
  60822. */
  60823. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60824. return this._sourceMesh.isVerticesDataPresent(kind);
  60825. };
  60826. /**
  60827. * Returns an array of indices (IndicesArray).
  60828. */
  60829. InstancedMesh.prototype.getIndices = function () {
  60830. return this._sourceMesh.getIndices();
  60831. };
  60832. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60833. get: function () {
  60834. return this._sourceMesh._positions;
  60835. },
  60836. enumerable: true,
  60837. configurable: true
  60838. });
  60839. /**
  60840. * Sets a new updated BoundingInfo to the mesh.
  60841. * Returns the mesh.
  60842. */
  60843. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60844. var meshBB = this._sourceMesh.getBoundingInfo();
  60845. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60846. this._updateBoundingInfo();
  60847. return this;
  60848. };
  60849. InstancedMesh.prototype._preActivate = function () {
  60850. if (this._currentLOD) {
  60851. this._currentLOD._preActivate();
  60852. }
  60853. return this;
  60854. };
  60855. InstancedMesh.prototype._activate = function (renderId) {
  60856. if (this._currentLOD) {
  60857. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60858. }
  60859. return this;
  60860. };
  60861. /**
  60862. * Returns the current associated LOD AbstractMesh.
  60863. */
  60864. InstancedMesh.prototype.getLOD = function (camera) {
  60865. if (!camera) {
  60866. return this;
  60867. }
  60868. var boundingInfo = this.getBoundingInfo();
  60869. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60870. if (this._currentLOD === this.sourceMesh) {
  60871. return this;
  60872. }
  60873. return this._currentLOD;
  60874. };
  60875. InstancedMesh.prototype._syncSubMeshes = function () {
  60876. this.releaseSubMeshes();
  60877. if (this._sourceMesh.subMeshes) {
  60878. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60879. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60880. }
  60881. }
  60882. return this;
  60883. };
  60884. InstancedMesh.prototype._generatePointsArray = function () {
  60885. return this._sourceMesh._generatePointsArray();
  60886. };
  60887. /**
  60888. * Creates a new InstancedMesh from the current mesh.
  60889. * - name (string) : the cloned mesh name
  60890. * - newParent (optional Node) : the optional Node to parent the clone to.
  60891. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60892. *
  60893. * Returns the clone.
  60894. */
  60895. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60896. var result = this._sourceMesh.createInstance(name);
  60897. // Deep copy
  60898. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60899. // Bounding info
  60900. this.refreshBoundingInfo();
  60901. // Parent
  60902. if (newParent) {
  60903. result.parent = newParent;
  60904. }
  60905. if (!doNotCloneChildren) {
  60906. // Children
  60907. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60908. var mesh = this.getScene().meshes[index];
  60909. if (mesh.parent === this) {
  60910. mesh.clone(mesh.name, result);
  60911. }
  60912. }
  60913. }
  60914. result.computeWorldMatrix(true);
  60915. return result;
  60916. };
  60917. /**
  60918. * Disposes the InstancedMesh.
  60919. * Returns nothing.
  60920. */
  60921. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60922. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60923. // Remove from mesh
  60924. var index = this._sourceMesh.instances.indexOf(this);
  60925. this._sourceMesh.instances.splice(index, 1);
  60926. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60927. };
  60928. return InstancedMesh;
  60929. }(BABYLON.AbstractMesh));
  60930. BABYLON.InstancedMesh = InstancedMesh;
  60931. })(BABYLON || (BABYLON = {}));
  60932. //# sourceMappingURL=babylon.instancedMesh.js.map
  60933. var BABYLON;
  60934. (function (BABYLON) {
  60935. var LinesMesh = /** @class */ (function (_super) {
  60936. __extends(LinesMesh, _super);
  60937. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60938. if (scene === void 0) { scene = null; }
  60939. if (parent === void 0) { parent = null; }
  60940. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60941. _this.useVertexColor = useVertexColor;
  60942. _this.useVertexAlpha = useVertexAlpha;
  60943. _this.color = new BABYLON.Color3(1, 1, 1);
  60944. _this.alpha = 1;
  60945. if (source) {
  60946. _this.color = source.color.clone();
  60947. _this.alpha = source.alpha;
  60948. _this.useVertexColor = source.useVertexColor;
  60949. _this.useVertexAlpha = source.useVertexAlpha;
  60950. }
  60951. _this._intersectionThreshold = 0.1;
  60952. var defines = [];
  60953. var options = {
  60954. attributes: [BABYLON.VertexBuffer.PositionKind],
  60955. uniforms: ["world", "viewProjection"],
  60956. needAlphaBlending: true,
  60957. defines: defines
  60958. };
  60959. if (useVertexAlpha === false) {
  60960. options.needAlphaBlending = false;
  60961. }
  60962. if (!useVertexColor) {
  60963. options.uniforms.push("color");
  60964. }
  60965. else {
  60966. options.defines.push("#define VERTEXCOLOR");
  60967. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60968. }
  60969. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60970. return _this;
  60971. }
  60972. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60973. /**
  60974. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60975. * This margin is expressed in world space coordinates, so its value may vary.
  60976. * Default value is 0.1
  60977. * @returns the intersection Threshold value.
  60978. */
  60979. get: function () {
  60980. return this._intersectionThreshold;
  60981. },
  60982. /**
  60983. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60984. * This margin is expressed in world space coordinates, so its value may vary.
  60985. * @param value the new threshold to apply
  60986. */
  60987. set: function (value) {
  60988. if (this._intersectionThreshold === value) {
  60989. return;
  60990. }
  60991. this._intersectionThreshold = value;
  60992. if (this.geometry) {
  60993. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60994. }
  60995. },
  60996. enumerable: true,
  60997. configurable: true
  60998. });
  60999. /**
  61000. * Returns the string "LineMesh"
  61001. */
  61002. LinesMesh.prototype.getClassName = function () {
  61003. return "LinesMesh";
  61004. };
  61005. Object.defineProperty(LinesMesh.prototype, "material", {
  61006. get: function () {
  61007. return this._colorShader;
  61008. },
  61009. set: function (value) {
  61010. // Do nothing
  61011. },
  61012. enumerable: true,
  61013. configurable: true
  61014. });
  61015. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61016. get: function () {
  61017. return false;
  61018. },
  61019. enumerable: true,
  61020. configurable: true
  61021. });
  61022. LinesMesh.prototype.createInstance = function (name) {
  61023. throw new Error("LinesMeshes do not support createInstance.");
  61024. };
  61025. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61026. if (!this._geometry) {
  61027. return this;
  61028. }
  61029. // VBOs
  61030. this._geometry._bind(this._colorShader.getEffect());
  61031. // Color
  61032. if (!this.useVertexColor) {
  61033. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61034. }
  61035. return this;
  61036. };
  61037. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61038. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61039. return this;
  61040. }
  61041. var engine = this.getScene().getEngine();
  61042. // Draw order
  61043. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61044. return this;
  61045. };
  61046. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61047. this._colorShader.dispose();
  61048. _super.prototype.dispose.call(this, doNotRecurse);
  61049. };
  61050. /**
  61051. * Returns a new LineMesh object cloned from the current one.
  61052. */
  61053. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61054. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61055. };
  61056. return LinesMesh;
  61057. }(BABYLON.Mesh));
  61058. BABYLON.LinesMesh = LinesMesh;
  61059. })(BABYLON || (BABYLON = {}));
  61060. //# sourceMappingURL=babylon.linesMesh.js.map
  61061. var BABYLON;
  61062. (function (BABYLON) {
  61063. /**
  61064. * Class containing static functions to help procedurally build meshes
  61065. */
  61066. var MeshBuilder = /** @class */ (function () {
  61067. function MeshBuilder() {
  61068. }
  61069. MeshBuilder.updateSideOrientation = function (orientation) {
  61070. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61071. return BABYLON.Mesh.DOUBLESIDE;
  61072. }
  61073. if (orientation === undefined || orientation === null) {
  61074. return BABYLON.Mesh.FRONTSIDE;
  61075. }
  61076. return orientation;
  61077. };
  61078. /**
  61079. * Creates a box mesh
  61080. * * The parameter `size` sets the size (float) of each box side (default 1)
  61081. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61082. * * 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)
  61083. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61084. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61085. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61086. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61087. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61088. * @param name defines the name of the mesh
  61089. * @param options defines the options used to create the mesh
  61090. * @param scene defines the hosting scene
  61091. * @returns the box mesh
  61092. */
  61093. MeshBuilder.CreateBox = function (name, options, scene) {
  61094. if (scene === void 0) { scene = null; }
  61095. var box = new BABYLON.Mesh(name, scene);
  61096. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61097. box._originalBuilderSideOrientation = options.sideOrientation;
  61098. var vertexData = BABYLON.VertexData.CreateBox(options);
  61099. vertexData.applyToMesh(box, options.updatable);
  61100. return box;
  61101. };
  61102. /**
  61103. * Creates a sphere mesh
  61104. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61105. * * 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`)
  61106. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61107. * * 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
  61108. * * 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)
  61109. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61110. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61111. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61112. * @param name defines the name of the mesh
  61113. * @param options defines the options used to create the mesh
  61114. * @param scene defines the hosting scene
  61115. * @returns the sphere mesh
  61116. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61117. */
  61118. MeshBuilder.CreateSphere = function (name, options, scene) {
  61119. var sphere = new BABYLON.Mesh(name, scene);
  61120. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61121. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61122. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61123. vertexData.applyToMesh(sphere, options.updatable);
  61124. return sphere;
  61125. };
  61126. /**
  61127. * Creates a plane polygonal mesh. By default, this is a disc
  61128. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61129. * * 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
  61130. * * 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
  61131. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61132. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61133. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61134. * @param name defines the name of the mesh
  61135. * @param options defines the options used to create the mesh
  61136. * @param scene defines the hosting scene
  61137. * @returns the plane polygonal mesh
  61138. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61139. */
  61140. MeshBuilder.CreateDisc = function (name, options, scene) {
  61141. if (scene === void 0) { scene = null; }
  61142. var disc = new BABYLON.Mesh(name, scene);
  61143. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61144. disc._originalBuilderSideOrientation = options.sideOrientation;
  61145. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61146. vertexData.applyToMesh(disc, options.updatable);
  61147. return disc;
  61148. };
  61149. /**
  61150. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61151. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61152. * * 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`)
  61153. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61154. * * 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
  61155. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61156. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61157. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61158. * @param name defines the name of the mesh
  61159. * @param options defines the options used to create the mesh
  61160. * @param scene defines the hosting scene
  61161. * @returns the icosahedron mesh
  61162. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61163. */
  61164. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61165. var sphere = new BABYLON.Mesh(name, scene);
  61166. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61167. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61168. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61169. vertexData.applyToMesh(sphere, options.updatable);
  61170. return sphere;
  61171. };
  61172. ;
  61173. /**
  61174. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61175. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61176. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61177. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61178. * * 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
  61179. * * 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
  61180. * * 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
  61181. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61182. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61183. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61184. * * 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
  61185. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61186. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  61187. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61188. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61189. * @param name defines the name of the mesh
  61190. * @param options defines the options used to create the mesh
  61191. * @param scene defines the hosting scene
  61192. * @returns the ribbon mesh
  61193. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61194. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61195. */
  61196. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61197. if (scene === void 0) { scene = null; }
  61198. var pathArray = options.pathArray;
  61199. var closeArray = options.closeArray;
  61200. var closePath = options.closePath;
  61201. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61202. var instance = options.instance;
  61203. var updatable = options.updatable;
  61204. if (instance) { // existing ribbon instance update
  61205. // positionFunction : ribbon case
  61206. // only pathArray and sideOrientation parameters are taken into account for positions update
  61207. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61208. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61209. var positionFunction = function (positions) {
  61210. var minlg = pathArray[0].length;
  61211. var i = 0;
  61212. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61213. for (var si = 1; si <= ns; si++) {
  61214. for (var p = 0; p < pathArray.length; p++) {
  61215. var path = pathArray[p];
  61216. var l = path.length;
  61217. minlg = (minlg < l) ? minlg : l;
  61218. var j = 0;
  61219. while (j < minlg) {
  61220. positions[i] = path[j].x;
  61221. positions[i + 1] = path[j].y;
  61222. positions[i + 2] = path[j].z;
  61223. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61224. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61225. }
  61226. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61227. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61228. }
  61229. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61230. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61231. }
  61232. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61233. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61234. }
  61235. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61236. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61237. }
  61238. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61239. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61240. }
  61241. j++;
  61242. i += 3;
  61243. }
  61244. if (instance._closePath) {
  61245. positions[i] = path[0].x;
  61246. positions[i + 1] = path[0].y;
  61247. positions[i + 2] = path[0].z;
  61248. i += 3;
  61249. }
  61250. }
  61251. }
  61252. };
  61253. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61254. positionFunction(positions);
  61255. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61256. instance._boundingInfo.update(instance._worldMatrix);
  61257. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61258. if (options.colors) {
  61259. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61260. for (var c = 0; c < options.colors.length; c++) {
  61261. colors[c * 4] = options.colors[c].r;
  61262. colors[c * 4 + 1] = options.colors[c].g;
  61263. colors[c * 4 + 2] = options.colors[c].b;
  61264. colors[c * 4 + 3] = options.colors[c].a;
  61265. }
  61266. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61267. }
  61268. if (options.uvs) {
  61269. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61270. for (var i = 0; i < options.uvs.length; i++) {
  61271. uvs[i * 2] = options.uvs[i].x;
  61272. uvs[i * 2 + 1] = options.uvs[i].y;
  61273. }
  61274. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61275. }
  61276. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61277. var indices = instance.getIndices();
  61278. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61279. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61280. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61281. if (instance._closePath) {
  61282. var indexFirst = 0;
  61283. var indexLast = 0;
  61284. for (var p = 0; p < pathArray.length; p++) {
  61285. indexFirst = instance._idx[p] * 3;
  61286. if (p + 1 < pathArray.length) {
  61287. indexLast = (instance._idx[p + 1] - 1) * 3;
  61288. }
  61289. else {
  61290. indexLast = normals.length - 3;
  61291. }
  61292. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61293. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61294. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61295. normals[indexLast] = normals[indexFirst];
  61296. normals[indexLast + 1] = normals[indexFirst + 1];
  61297. normals[indexLast + 2] = normals[indexFirst + 2];
  61298. }
  61299. }
  61300. if (!(instance.areNormalsFrozen)) {
  61301. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61302. }
  61303. }
  61304. return instance;
  61305. }
  61306. else { // new ribbon creation
  61307. var ribbon = new BABYLON.Mesh(name, scene);
  61308. ribbon._originalBuilderSideOrientation = sideOrientation;
  61309. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61310. if (closePath) {
  61311. ribbon._idx = vertexData._idx;
  61312. }
  61313. ribbon._closePath = closePath;
  61314. ribbon._closeArray = closeArray;
  61315. vertexData.applyToMesh(ribbon, updatable);
  61316. return ribbon;
  61317. }
  61318. };
  61319. /**
  61320. * Creates a cylinder or a cone mesh
  61321. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61322. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61323. * * 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.
  61324. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61325. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61326. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61327. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61328. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61329. * * 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).
  61330. * * 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
  61331. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61332. * * 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
  61333. * * 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.
  61334. * * If `enclose` is false, a ring surface is one element.
  61335. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61336. * * 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
  61337. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61338. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61339. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61340. * @param name defines the name of the mesh
  61341. * @param options defines the options used to create the mesh
  61342. * @param scene defines the hosting scene
  61343. * @returns the cylinder mesh
  61344. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61345. */
  61346. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61347. var cylinder = new BABYLON.Mesh(name, scene);
  61348. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61349. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61350. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61351. vertexData.applyToMesh(cylinder, options.updatable);
  61352. return cylinder;
  61353. };
  61354. /**
  61355. * Creates a torus mesh
  61356. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61357. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61358. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61359. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61360. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61361. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61362. * @param name defines the name of the mesh
  61363. * @param options defines the options used to create the mesh
  61364. * @param scene defines the hosting scene
  61365. * @returns the torus mesh
  61366. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61367. */
  61368. MeshBuilder.CreateTorus = function (name, options, scene) {
  61369. var torus = new BABYLON.Mesh(name, scene);
  61370. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61371. torus._originalBuilderSideOrientation = options.sideOrientation;
  61372. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61373. vertexData.applyToMesh(torus, options.updatable);
  61374. return torus;
  61375. };
  61376. /**
  61377. * Creates a torus knot mesh
  61378. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61379. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61380. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61381. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61382. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61383. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61384. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61385. * @param name defines the name of the mesh
  61386. * @param options defines the options used to create the mesh
  61387. * @param scene defines the hosting scene
  61388. * @returns the torus knot mesh
  61389. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61390. */
  61391. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61392. var torusKnot = new BABYLON.Mesh(name, scene);
  61393. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61394. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61395. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61396. vertexData.applyToMesh(torusKnot, options.updatable);
  61397. return torusKnot;
  61398. };
  61399. /**
  61400. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61401. * * 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
  61402. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61403. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61404. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61405. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61406. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61407. * * 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
  61408. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61409. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61410. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61411. * @param name defines the name of the new line system
  61412. * @param options defines the options used to create the line system
  61413. * @param scene defines the hosting scene
  61414. * @returns a new line system mesh
  61415. */
  61416. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61417. var instance = options.instance;
  61418. var lines = options.lines;
  61419. var colors = options.colors;
  61420. if (instance) { // lines update
  61421. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61422. var vertexColor;
  61423. var lineColors;
  61424. if (colors) {
  61425. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61426. }
  61427. var i = 0;
  61428. var c = 0;
  61429. for (var l = 0; l < lines.length; l++) {
  61430. var points = lines[l];
  61431. for (var p = 0; p < points.length; p++) {
  61432. positions[i] = points[p].x;
  61433. positions[i + 1] = points[p].y;
  61434. positions[i + 2] = points[p].z;
  61435. if (colors && vertexColor) {
  61436. lineColors = colors[l];
  61437. vertexColor[c] = lineColors[p].r;
  61438. vertexColor[c + 1] = lineColors[p].g;
  61439. vertexColor[c + 2] = lineColors[p].b;
  61440. vertexColor[c + 3] = lineColors[p].a;
  61441. c += 4;
  61442. }
  61443. i += 3;
  61444. }
  61445. }
  61446. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61447. if (colors && vertexColor) {
  61448. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61449. }
  61450. return instance;
  61451. }
  61452. // line system creation
  61453. var useVertexColor = (colors) ? true : false;
  61454. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61455. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61456. vertexData.applyToMesh(lineSystem, options.updatable);
  61457. return lineSystem;
  61458. };
  61459. /**
  61460. * Creates a line mesh
  61461. * 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
  61462. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61463. * * The parameter `points` is an array successive Vector3
  61464. * * 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
  61465. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61466. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61467. * * When updating an instance, remember that only point positions can change, not the number of points
  61468. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61469. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61470. * @param name defines the name of the new line system
  61471. * @param options defines the options used to create the line system
  61472. * @param scene defines the hosting scene
  61473. * @returns a new line mesh
  61474. */
  61475. MeshBuilder.CreateLines = function (name, options, scene) {
  61476. if (scene === void 0) { scene = null; }
  61477. var colors = (options.colors) ? [options.colors] : null;
  61478. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61479. return lines;
  61480. };
  61481. /**
  61482. * Creates a dashed line mesh
  61483. * * 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
  61484. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61485. * * The parameter `points` is an array successive Vector3
  61486. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61487. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61488. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61489. * * 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
  61490. * * When updating an instance, remember that only point positions can change, not the number of points
  61491. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61492. * @param name defines the name of the mesh
  61493. * @param options defines the options used to create the mesh
  61494. * @param scene defines the hosting scene
  61495. * @returns the dashed line mesh
  61496. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61497. */
  61498. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61499. if (scene === void 0) { scene = null; }
  61500. var points = options.points;
  61501. var instance = options.instance;
  61502. var gapSize = options.gapSize || 1;
  61503. var dashSize = options.dashSize || 3;
  61504. if (instance) { // dashed lines update
  61505. var positionFunction = function (positions) {
  61506. var curvect = BABYLON.Vector3.Zero();
  61507. var nbSeg = positions.length / 6;
  61508. var lg = 0;
  61509. var nb = 0;
  61510. var shft = 0;
  61511. var dashshft = 0;
  61512. var curshft = 0;
  61513. var p = 0;
  61514. var i = 0;
  61515. var j = 0;
  61516. for (i = 0; i < points.length - 1; i++) {
  61517. points[i + 1].subtractToRef(points[i], curvect);
  61518. lg += curvect.length();
  61519. }
  61520. shft = lg / nbSeg;
  61521. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61522. for (i = 0; i < points.length - 1; i++) {
  61523. points[i + 1].subtractToRef(points[i], curvect);
  61524. nb = Math.floor(curvect.length() / shft);
  61525. curvect.normalize();
  61526. j = 0;
  61527. while (j < nb && p < positions.length) {
  61528. curshft = shft * j;
  61529. positions[p] = points[i].x + curshft * curvect.x;
  61530. positions[p + 1] = points[i].y + curshft * curvect.y;
  61531. positions[p + 2] = points[i].z + curshft * curvect.z;
  61532. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61533. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61534. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61535. p += 6;
  61536. j++;
  61537. }
  61538. }
  61539. while (p < positions.length) {
  61540. positions[p] = points[i].x;
  61541. positions[p + 1] = points[i].y;
  61542. positions[p + 2] = points[i].z;
  61543. p += 3;
  61544. }
  61545. };
  61546. instance.updateMeshPositions(positionFunction, false);
  61547. return instance;
  61548. }
  61549. // dashed lines creation
  61550. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61551. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61552. vertexData.applyToMesh(dashedLines, options.updatable);
  61553. dashedLines.dashSize = dashSize;
  61554. dashedLines.gapSize = gapSize;
  61555. return dashedLines;
  61556. };
  61557. /**
  61558. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61559. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61560. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61561. * * 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.
  61562. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61563. * * 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
  61564. * * 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
  61565. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61566. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61567. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61568. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61569. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61570. * @param name defines the name of the mesh
  61571. * @param options defines the options used to create the mesh
  61572. * @param scene defines the hosting scene
  61573. * @returns the extruded shape mesh
  61574. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61575. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61576. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61577. */
  61578. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61579. if (scene === void 0) { scene = null; }
  61580. var path = options.path;
  61581. var shape = options.shape;
  61582. var scale = options.scale || 1;
  61583. var rotation = options.rotation || 0;
  61584. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61585. var updatable = options.updatable;
  61586. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61587. var instance = options.instance || null;
  61588. var invertUV = options.invertUV || false;
  61589. 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);
  61590. };
  61591. /**
  61592. * Creates an custom extruded shape mesh.
  61593. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61594. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61595. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61596. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61597. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61598. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  61599. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61600. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61601. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61602. * * 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
  61603. * * 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
  61604. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61605. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61606. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61607. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61608. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61609. * @param name defines the name of the mesh
  61610. * @param options defines the options used to create the mesh
  61611. * @param scene defines the hosting scene
  61612. * @returns the custom extruded shape mesh
  61613. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61614. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61615. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61616. */
  61617. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61618. var path = options.path;
  61619. var shape = options.shape;
  61620. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61621. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61622. var ribbonCloseArray = options.ribbonCloseArray || false;
  61623. var ribbonClosePath = options.ribbonClosePath || false;
  61624. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61625. var updatable = options.updatable;
  61626. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61627. var instance = options.instance;
  61628. var invertUV = options.invertUV || false;
  61629. 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);
  61630. };
  61631. /**
  61632. * Creates lathe mesh.
  61633. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61634. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61635. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61636. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61637. * * 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
  61638. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61639. * * 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
  61640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61641. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61642. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61643. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61644. * @param name defines the name of the mesh
  61645. * @param options defines the options used to create the mesh
  61646. * @param scene defines the hosting scene
  61647. * @returns the lathe mesh
  61648. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61649. */
  61650. MeshBuilder.CreateLathe = function (name, options, scene) {
  61651. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61652. var closed = (options.closed === undefined) ? true : options.closed;
  61653. var shape = options.shape;
  61654. var radius = options.radius || 1;
  61655. var tessellation = options.tessellation || 64;
  61656. var updatable = options.updatable;
  61657. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61658. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61659. var pi2 = Math.PI * 2;
  61660. var paths = new Array();
  61661. var invertUV = options.invertUV || false;
  61662. var i = 0;
  61663. var p = 0;
  61664. var step = pi2 / tessellation * arc;
  61665. var rotated;
  61666. var path = new Array();
  61667. for (i = 0; i <= tessellation; i++) {
  61668. var path = [];
  61669. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61670. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61671. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61672. }
  61673. for (p = 0; p < shape.length; p++) {
  61674. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61675. path.push(rotated);
  61676. }
  61677. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61678. 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));
  61679. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61680. }
  61681. paths.push(path);
  61682. }
  61683. // lathe ribbon
  61684. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61685. return lathe;
  61686. };
  61687. /**
  61688. * Creates a plane mesh
  61689. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61690. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61691. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61692. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61693. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61694. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61695. * @param name defines the name of the mesh
  61696. * @param options defines the options used to create the mesh
  61697. * @param scene defines the hosting scene
  61698. * @returns the plane mesh
  61699. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61700. */
  61701. MeshBuilder.CreatePlane = function (name, options, scene) {
  61702. var plane = new BABYLON.Mesh(name, scene);
  61703. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61704. plane._originalBuilderSideOrientation = options.sideOrientation;
  61705. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61706. vertexData.applyToMesh(plane, options.updatable);
  61707. if (options.sourcePlane) {
  61708. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61709. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61710. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61711. plane.rotate(vectorProduct, product);
  61712. }
  61713. return plane;
  61714. };
  61715. /**
  61716. * Creates a ground mesh
  61717. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61718. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61719. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61720. * @param name defines the name of the mesh
  61721. * @param options defines the options used to create the mesh
  61722. * @param scene defines the hosting scene
  61723. * @returns the ground mesh
  61724. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61725. */
  61726. MeshBuilder.CreateGround = function (name, options, scene) {
  61727. var ground = new BABYLON.GroundMesh(name, scene);
  61728. ground._setReady(false);
  61729. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61730. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61731. ground._width = options.width || 1;
  61732. ground._height = options.height || 1;
  61733. ground._maxX = ground._width / 2;
  61734. ground._maxZ = ground._height / 2;
  61735. ground._minX = -ground._maxX;
  61736. ground._minZ = -ground._maxZ;
  61737. var vertexData = BABYLON.VertexData.CreateGround(options);
  61738. vertexData.applyToMesh(ground, options.updatable);
  61739. ground._setReady(true);
  61740. return ground;
  61741. };
  61742. /**
  61743. * Creates a tiled ground mesh
  61744. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61745. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61746. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61747. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61748. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61749. * @param name defines the name of the mesh
  61750. * @param options defines the options used to create the mesh
  61751. * @param scene defines the hosting scene
  61752. * @returns the tiled ground mesh
  61753. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61754. */
  61755. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61756. var tiledGround = new BABYLON.Mesh(name, scene);
  61757. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61758. vertexData.applyToMesh(tiledGround, options.updatable);
  61759. return tiledGround;
  61760. };
  61761. /**
  61762. * Creates a ground mesh from a height map
  61763. * * The parameter `url` sets the URL of the height map image resource.
  61764. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61765. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61766. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61767. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61768. * * 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.
  61769. * * 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).
  61770. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61771. * @param name defines the name of the mesh
  61772. * @param url defines the url to the height map
  61773. * @param options defines the options used to create the mesh
  61774. * @param scene defines the hosting scene
  61775. * @returns the ground mesh
  61776. * @see http://doc.babylonjs.com/babylon101/height_map
  61777. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61778. */
  61779. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61780. var width = options.width || 10.0;
  61781. var height = options.height || 10.0;
  61782. var subdivisions = options.subdivisions || 1 | 0;
  61783. var minHeight = options.minHeight || 0.0;
  61784. var maxHeight = options.maxHeight || 1.0;
  61785. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61786. var updatable = options.updatable;
  61787. var onReady = options.onReady;
  61788. var ground = new BABYLON.GroundMesh(name, scene);
  61789. ground._subdivisionsX = subdivisions;
  61790. ground._subdivisionsY = subdivisions;
  61791. ground._width = width;
  61792. ground._height = height;
  61793. ground._maxX = ground._width / 2.0;
  61794. ground._maxZ = ground._height / 2.0;
  61795. ground._minX = -ground._maxX;
  61796. ground._minZ = -ground._maxZ;
  61797. ground._setReady(false);
  61798. var onload = function (img) {
  61799. // Getting height map data
  61800. var canvas = document.createElement("canvas");
  61801. var context = canvas.getContext("2d");
  61802. if (!context) {
  61803. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61804. }
  61805. if (scene.isDisposed) {
  61806. return;
  61807. }
  61808. var bufferWidth = img.width;
  61809. var bufferHeight = img.height;
  61810. canvas.width = bufferWidth;
  61811. canvas.height = bufferHeight;
  61812. context.drawImage(img, 0, 0);
  61813. // Create VertexData from map data
  61814. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61815. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61816. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61817. width: width, height: height,
  61818. subdivisions: subdivisions,
  61819. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61820. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61821. });
  61822. vertexData.applyToMesh(ground, updatable);
  61823. //execute ready callback, if set
  61824. if (onReady) {
  61825. onReady(ground);
  61826. }
  61827. ground._setReady(true);
  61828. };
  61829. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61830. return ground;
  61831. };
  61832. /**
  61833. * Creates a polygon mesh
  61834. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61835. * * 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
  61836. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61837. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61838. * * 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)
  61839. * * Remember you can only change the shape positions, not their number when updating a polygon
  61840. * @param name defines the name of the mesh
  61841. * @param options defines the options used to create the mesh
  61842. * @param scene defines the hosting scene
  61843. * @returns the polygon mesh
  61844. */
  61845. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61846. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61847. var shape = options.shape;
  61848. var holes = options.holes || [];
  61849. var depth = options.depth || 0;
  61850. var contours = [];
  61851. var hole = [];
  61852. for (var i = 0; i < shape.length; i++) {
  61853. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61854. }
  61855. var epsilon = 0.00000001;
  61856. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61857. contours.pop();
  61858. }
  61859. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61860. for (var hNb = 0; hNb < holes.length; hNb++) {
  61861. hole = [];
  61862. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61863. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61864. }
  61865. polygonTriangulation.addHole(hole);
  61866. }
  61867. var polygon = polygonTriangulation.build(options.updatable, depth);
  61868. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61869. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61870. vertexData.applyToMesh(polygon, options.updatable);
  61871. return polygon;
  61872. };
  61873. ;
  61874. /**
  61875. * Creates an extruded polygon mesh, with depth in the Y direction.
  61876. * * 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)
  61877. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61878. * @param name defines the name of the mesh
  61879. * @param options defines the options used to create the mesh
  61880. * @param scene defines the hosting scene
  61881. * @returns the polygon mesh
  61882. */
  61883. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61884. return MeshBuilder.CreatePolygon(name, options, scene);
  61885. };
  61886. ;
  61887. /**
  61888. * Creates a tube mesh.
  61889. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61890. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61891. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61892. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61893. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61894. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61895. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61896. * * 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
  61897. * * 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
  61898. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61899. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61900. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61901. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61902. * @param name defines the name of the mesh
  61903. * @param options defines the options used to create the mesh
  61904. * @param scene defines the hosting scene
  61905. * @returns the tube mesh
  61906. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61907. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61908. */
  61909. MeshBuilder.CreateTube = function (name, options, scene) {
  61910. var path = options.path;
  61911. var instance = options.instance;
  61912. var radius = 1.0;
  61913. if (instance) {
  61914. radius = instance.radius;
  61915. }
  61916. if (options.radius !== undefined) {
  61917. radius = options.radius;
  61918. }
  61919. ;
  61920. var tessellation = options.tessellation || 64 | 0;
  61921. var radiusFunction = options.radiusFunction || null;
  61922. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61923. var invertUV = options.invertUV || false;
  61924. var updatable = options.updatable;
  61925. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61926. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61927. // tube geometry
  61928. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61929. var tangents = path3D.getTangents();
  61930. var normals = path3D.getNormals();
  61931. var distances = path3D.getDistances();
  61932. var pi2 = Math.PI * 2;
  61933. var step = pi2 / tessellation * arc;
  61934. var returnRadius = function () { return radius; };
  61935. var radiusFunctionFinal = radiusFunction || returnRadius;
  61936. var circlePath;
  61937. var rad;
  61938. var normal;
  61939. var rotated;
  61940. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61941. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61942. for (var i = 0; i < path.length; i++) {
  61943. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61944. circlePath = Array(); // current circle array
  61945. normal = normals[i]; // current normal
  61946. for (var t = 0; t < tessellation; t++) {
  61947. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61948. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61949. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61950. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61951. circlePath[t] = rotated;
  61952. }
  61953. circlePaths[index] = circlePath;
  61954. index++;
  61955. }
  61956. // cap
  61957. var capPath = function (nbPoints, pathIndex) {
  61958. var pointCap = Array();
  61959. for (var i = 0; i < nbPoints; i++) {
  61960. pointCap.push(path[pathIndex]);
  61961. }
  61962. return pointCap;
  61963. };
  61964. switch (cap) {
  61965. case BABYLON.Mesh.NO_CAP:
  61966. break;
  61967. case BABYLON.Mesh.CAP_START:
  61968. circlePaths[0] = capPath(tessellation, 0);
  61969. circlePaths[1] = circlePaths[2].slice(0);
  61970. break;
  61971. case BABYLON.Mesh.CAP_END:
  61972. circlePaths[index] = circlePaths[index - 1].slice(0);
  61973. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61974. break;
  61975. case BABYLON.Mesh.CAP_ALL:
  61976. circlePaths[0] = capPath(tessellation, 0);
  61977. circlePaths[1] = circlePaths[2].slice(0);
  61978. circlePaths[index] = circlePaths[index - 1].slice(0);
  61979. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61980. break;
  61981. default:
  61982. break;
  61983. }
  61984. return circlePaths;
  61985. };
  61986. var path3D;
  61987. var pathArray;
  61988. if (instance) { // tube update
  61989. var arc = options.arc || instance.arc;
  61990. path3D = (instance.path3D).update(path);
  61991. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61992. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61993. instance.path3D = path3D;
  61994. instance.pathArray = pathArray;
  61995. instance.arc = arc;
  61996. instance.radius = radius;
  61997. return instance;
  61998. }
  61999. // tube creation
  62000. path3D = new BABYLON.Path3D(path);
  62001. var newPathArray = new Array();
  62002. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62003. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62004. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62005. tube.pathArray = pathArray;
  62006. tube.path3D = path3D;
  62007. tube.tessellation = tessellation;
  62008. tube.cap = cap;
  62009. tube.arc = options.arc;
  62010. tube.radius = radius;
  62011. return tube;
  62012. };
  62013. /**
  62014. * Creates a polyhedron mesh
  62015. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  62016. * * The parameter `size` (positive float, default 1) sets the polygon size
  62017. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62018. * * 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`
  62019. * * 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
  62020. * * 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)`)
  62021. * * 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
  62022. * * 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
  62023. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62024. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62025. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62026. * @param name defines the name of the mesh
  62027. * @param options defines the options used to create the mesh
  62028. * @param scene defines the hosting scene
  62029. * @returns the polyhedron mesh
  62030. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62031. */
  62032. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62033. var polyhedron = new BABYLON.Mesh(name, scene);
  62034. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62035. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62036. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62037. vertexData.applyToMesh(polyhedron, options.updatable);
  62038. return polyhedron;
  62039. };
  62040. /**
  62041. * Creates a decal mesh.
  62042. * 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
  62043. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62044. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62045. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62046. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62047. * @param name defines the name of the mesh
  62048. * @param sourceMesh defines the mesh where the decal must be applied
  62049. * @param options defines the options used to create the mesh
  62050. * @param scene defines the hosting scene
  62051. * @returns the decal mesh
  62052. * @see http://doc.babylonjs.com/how_to/decals
  62053. */
  62054. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62055. var indices = sourceMesh.getIndices();
  62056. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62057. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62058. var position = options.position || BABYLON.Vector3.Zero();
  62059. var normal = options.normal || BABYLON.Vector3.Up();
  62060. var size = options.size || BABYLON.Vector3.One();
  62061. var angle = options.angle || 0;
  62062. // Getting correct rotation
  62063. if (!normal) {
  62064. var target = new BABYLON.Vector3(0, 0, 1);
  62065. var camera = sourceMesh.getScene().activeCamera;
  62066. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62067. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62068. }
  62069. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62070. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62071. var pitch = Math.atan2(normal.y, len);
  62072. // Matrix
  62073. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62074. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62075. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62076. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62077. var vertexData = new BABYLON.VertexData();
  62078. vertexData.indices = [];
  62079. vertexData.positions = [];
  62080. vertexData.normals = [];
  62081. vertexData.uvs = [];
  62082. var currentVertexDataIndex = 0;
  62083. var extractDecalVector3 = function (indexId) {
  62084. var result = new BABYLON.PositionNormalVertex();
  62085. if (!indices || !positions || !normals) {
  62086. return result;
  62087. }
  62088. var vertexId = indices[indexId];
  62089. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62090. // Send vector to decal local world
  62091. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62092. // Get normal
  62093. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62094. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62095. return result;
  62096. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62097. var clip = function (vertices, axis) {
  62098. if (vertices.length === 0) {
  62099. return vertices;
  62100. }
  62101. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62102. var clipVertices = function (v0, v1) {
  62103. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62104. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62105. };
  62106. var result = new Array();
  62107. for (var index = 0; index < vertices.length; index += 3) {
  62108. var v1Out;
  62109. var v2Out;
  62110. var v3Out;
  62111. var total = 0;
  62112. var nV1 = null;
  62113. var nV2 = null;
  62114. var nV3 = null;
  62115. var nV4 = null;
  62116. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62117. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62118. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62119. v1Out = d1 > 0;
  62120. v2Out = d2 > 0;
  62121. v3Out = d3 > 0;
  62122. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62123. switch (total) {
  62124. case 0:
  62125. result.push(vertices[index]);
  62126. result.push(vertices[index + 1]);
  62127. result.push(vertices[index + 2]);
  62128. break;
  62129. case 1:
  62130. if (v1Out) {
  62131. nV1 = vertices[index + 1];
  62132. nV2 = vertices[index + 2];
  62133. nV3 = clipVertices(vertices[index], nV1);
  62134. nV4 = clipVertices(vertices[index], nV2);
  62135. }
  62136. if (v2Out) {
  62137. nV1 = vertices[index];
  62138. nV2 = vertices[index + 2];
  62139. nV3 = clipVertices(vertices[index + 1], nV1);
  62140. nV4 = clipVertices(vertices[index + 1], nV2);
  62141. result.push(nV3);
  62142. result.push(nV2.clone());
  62143. result.push(nV1.clone());
  62144. result.push(nV2.clone());
  62145. result.push(nV3.clone());
  62146. result.push(nV4);
  62147. break;
  62148. }
  62149. if (v3Out) {
  62150. nV1 = vertices[index];
  62151. nV2 = vertices[index + 1];
  62152. nV3 = clipVertices(vertices[index + 2], nV1);
  62153. nV4 = clipVertices(vertices[index + 2], nV2);
  62154. }
  62155. if (nV1 && nV2 && nV3 && nV4) {
  62156. result.push(nV1.clone());
  62157. result.push(nV2.clone());
  62158. result.push(nV3);
  62159. result.push(nV4);
  62160. result.push(nV3.clone());
  62161. result.push(nV2.clone());
  62162. }
  62163. break;
  62164. case 2:
  62165. if (!v1Out) {
  62166. nV1 = vertices[index].clone();
  62167. nV2 = clipVertices(nV1, vertices[index + 1]);
  62168. nV3 = clipVertices(nV1, vertices[index + 2]);
  62169. result.push(nV1);
  62170. result.push(nV2);
  62171. result.push(nV3);
  62172. }
  62173. if (!v2Out) {
  62174. nV1 = vertices[index + 1].clone();
  62175. nV2 = clipVertices(nV1, vertices[index + 2]);
  62176. nV3 = clipVertices(nV1, vertices[index]);
  62177. result.push(nV1);
  62178. result.push(nV2);
  62179. result.push(nV3);
  62180. }
  62181. if (!v3Out) {
  62182. nV1 = vertices[index + 2].clone();
  62183. nV2 = clipVertices(nV1, vertices[index]);
  62184. nV3 = clipVertices(nV1, vertices[index + 1]);
  62185. result.push(nV1);
  62186. result.push(nV2);
  62187. result.push(nV3);
  62188. }
  62189. break;
  62190. case 3:
  62191. break;
  62192. }
  62193. }
  62194. return result;
  62195. };
  62196. for (var index = 0; index < indices.length; index += 3) {
  62197. var faceVertices = new Array();
  62198. faceVertices.push(extractDecalVector3(index));
  62199. faceVertices.push(extractDecalVector3(index + 1));
  62200. faceVertices.push(extractDecalVector3(index + 2));
  62201. // Clip
  62202. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62203. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62204. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62205. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62206. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62207. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62208. if (faceVertices.length === 0) {
  62209. continue;
  62210. }
  62211. // Add UVs and get back to world
  62212. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62213. var vertex = faceVertices[vIndex];
  62214. //TODO check for Int32Array | Uint32Array | Uint16Array
  62215. vertexData.indices.push(currentVertexDataIndex);
  62216. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62217. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62218. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62219. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62220. currentVertexDataIndex++;
  62221. }
  62222. }
  62223. // Return mesh
  62224. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62225. vertexData.applyToMesh(decal);
  62226. decal.position = position.clone();
  62227. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62228. return decal;
  62229. };
  62230. // Privates
  62231. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62232. // extrusion geometry
  62233. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62234. var tangents = path3D.getTangents();
  62235. var normals = path3D.getNormals();
  62236. var binormals = path3D.getBinormals();
  62237. var distances = path3D.getDistances();
  62238. var angle = 0;
  62239. var returnScale = function () { return scale !== null ? scale : 1; };
  62240. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62241. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62242. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62243. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62244. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62245. for (var i = 0; i < curve.length; i++) {
  62246. var shapePath = new Array();
  62247. var angleStep = rotate(i, distances[i]);
  62248. var scaleRatio = scl(i, distances[i]);
  62249. for (var p = 0; p < shape.length; p++) {
  62250. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62251. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62252. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62253. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62254. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62255. shapePath[p] = rotated;
  62256. }
  62257. shapePaths[index] = shapePath;
  62258. angle += angleStep;
  62259. index++;
  62260. }
  62261. // cap
  62262. var capPath = function (shapePath) {
  62263. var pointCap = Array();
  62264. var barycenter = BABYLON.Vector3.Zero();
  62265. var i;
  62266. for (i = 0; i < shapePath.length; i++) {
  62267. barycenter.addInPlace(shapePath[i]);
  62268. }
  62269. barycenter.scaleInPlace(1.0 / shapePath.length);
  62270. for (i = 0; i < shapePath.length; i++) {
  62271. pointCap.push(barycenter);
  62272. }
  62273. return pointCap;
  62274. };
  62275. switch (cap) {
  62276. case BABYLON.Mesh.NO_CAP:
  62277. break;
  62278. case BABYLON.Mesh.CAP_START:
  62279. shapePaths[0] = capPath(shapePaths[2]);
  62280. shapePaths[1] = shapePaths[2];
  62281. break;
  62282. case BABYLON.Mesh.CAP_END:
  62283. shapePaths[index] = shapePaths[index - 1];
  62284. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62285. break;
  62286. case BABYLON.Mesh.CAP_ALL:
  62287. shapePaths[0] = capPath(shapePaths[2]);
  62288. shapePaths[1] = shapePaths[2];
  62289. shapePaths[index] = shapePaths[index - 1];
  62290. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62291. break;
  62292. default:
  62293. break;
  62294. }
  62295. return shapePaths;
  62296. };
  62297. var path3D;
  62298. var pathArray;
  62299. if (instance) { // instance update
  62300. path3D = (instance.path3D).update(curve);
  62301. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62302. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62303. return instance;
  62304. }
  62305. // extruded shape creation
  62306. path3D = new BABYLON.Path3D(curve);
  62307. var newShapePaths = new Array();
  62308. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62309. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62310. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62311. extrudedGeneric.pathArray = pathArray;
  62312. extrudedGeneric.path3D = path3D;
  62313. extrudedGeneric.cap = cap;
  62314. return extrudedGeneric;
  62315. };
  62316. return MeshBuilder;
  62317. }());
  62318. BABYLON.MeshBuilder = MeshBuilder;
  62319. })(BABYLON || (BABYLON = {}));
  62320. //# sourceMappingURL=babylon.meshBuilder.js.map
  62321. var BABYLON;
  62322. (function (BABYLON) {
  62323. /**
  62324. * Draco compression (https://google.github.io/draco/)
  62325. *
  62326. * This class wraps the Draco module.
  62327. *
  62328. * **Encoder**
  62329. *
  62330. * The encoder is not currently implemented.
  62331. *
  62332. * **Decoder**
  62333. *
  62334. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62335. *
  62336. * To update the configuration, use the following code:
  62337. * ```javascript
  62338. * BABYLON.DracoCompression.Configuration = {
  62339. * decoder: {
  62340. * wasmUrl: "<url to the WebAssembly library>",
  62341. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62342. * fallbackUrl: "<url to the fallback JavaScript library>",
  62343. * }
  62344. * };
  62345. * ```
  62346. *
  62347. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62348. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62349. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62350. *
  62351. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62352. * ```javascript
  62353. * var dracoCompression = new BABYLON.DracoCompression();
  62354. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62355. * [BABYLON.VertexBuffer.PositionKind]: 0
  62356. * });
  62357. * ```
  62358. *
  62359. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62360. */
  62361. var DracoCompression = /** @class */ (function () {
  62362. /**
  62363. * Constructor
  62364. */
  62365. function DracoCompression() {
  62366. }
  62367. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62368. /**
  62369. * Returns true if the decoder is available.
  62370. */
  62371. get: function () {
  62372. if (typeof DracoDecoderModule !== "undefined") {
  62373. return true;
  62374. }
  62375. var decoder = DracoCompression.Configuration.decoder;
  62376. if (decoder) {
  62377. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62378. return true;
  62379. }
  62380. if (decoder.fallbackUrl) {
  62381. return true;
  62382. }
  62383. }
  62384. return false;
  62385. },
  62386. enumerable: true,
  62387. configurable: true
  62388. });
  62389. /**
  62390. * Stop all async operations and release resources.
  62391. */
  62392. DracoCompression.prototype.dispose = function () {
  62393. };
  62394. /**
  62395. * Decode Draco compressed mesh data to vertex data.
  62396. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62397. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62398. * @returns A promise that resolves with the decoded vertex data
  62399. */
  62400. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62401. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62402. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62403. var module = wrappedModule.module;
  62404. var vertexData = new BABYLON.VertexData();
  62405. var buffer = new module.DecoderBuffer();
  62406. buffer.Init(dataView, dataView.byteLength);
  62407. var decoder = new module.Decoder();
  62408. var geometry;
  62409. var status;
  62410. try {
  62411. var type = decoder.GetEncodedGeometryType(buffer);
  62412. switch (type) {
  62413. case module.TRIANGULAR_MESH:
  62414. geometry = new module.Mesh();
  62415. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62416. break;
  62417. case module.POINT_CLOUD:
  62418. geometry = new module.PointCloud();
  62419. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62420. break;
  62421. default:
  62422. throw new Error("Invalid geometry type " + type);
  62423. }
  62424. if (!status.ok() || !geometry.ptr) {
  62425. throw new Error(status.error_msg());
  62426. }
  62427. var numPoints = geometry.num_points();
  62428. if (type === module.TRIANGULAR_MESH) {
  62429. var numFaces = geometry.num_faces();
  62430. var faceIndices = new module.DracoInt32Array();
  62431. try {
  62432. var indices = new Uint32Array(numFaces * 3);
  62433. for (var i = 0; i < numFaces; i++) {
  62434. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62435. var offset = i * 3;
  62436. indices[offset + 0] = faceIndices.GetValue(0);
  62437. indices[offset + 1] = faceIndices.GetValue(1);
  62438. indices[offset + 2] = faceIndices.GetValue(2);
  62439. }
  62440. vertexData.indices = indices;
  62441. }
  62442. finally {
  62443. module.destroy(faceIndices);
  62444. }
  62445. }
  62446. for (var kind in attributes) {
  62447. var uniqueId = attributes[kind];
  62448. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62449. var dracoData = new module.DracoFloat32Array();
  62450. try {
  62451. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62452. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62453. for (var i = 0; i < babylonData.length; i++) {
  62454. babylonData[i] = dracoData.GetValue(i);
  62455. }
  62456. vertexData.set(babylonData, kind);
  62457. }
  62458. finally {
  62459. module.destroy(dracoData);
  62460. }
  62461. }
  62462. }
  62463. finally {
  62464. if (geometry) {
  62465. module.destroy(geometry);
  62466. }
  62467. module.destroy(decoder);
  62468. module.destroy(buffer);
  62469. }
  62470. return vertexData;
  62471. });
  62472. };
  62473. DracoCompression._GetDecoderModule = function () {
  62474. if (!DracoCompression._DecoderModulePromise) {
  62475. var promise = null;
  62476. var config_1 = {};
  62477. if (typeof DracoDecoderModule !== "undefined") {
  62478. promise = Promise.resolve();
  62479. }
  62480. else {
  62481. var decoder = DracoCompression.Configuration.decoder;
  62482. if (decoder) {
  62483. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62484. promise = Promise.all([
  62485. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62486. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62487. config_1.wasmBinary = data;
  62488. })
  62489. ]);
  62490. }
  62491. else if (decoder.fallbackUrl) {
  62492. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62493. }
  62494. }
  62495. }
  62496. if (!promise) {
  62497. throw new Error("Draco decoder module is not available");
  62498. }
  62499. DracoCompression._DecoderModulePromise = promise.then(function () {
  62500. return new Promise(function (resolve) {
  62501. config_1.onModuleLoaded = function (decoderModule) {
  62502. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62503. resolve({ module: decoderModule });
  62504. };
  62505. DracoDecoderModule(config_1);
  62506. });
  62507. });
  62508. }
  62509. return DracoCompression._DecoderModulePromise;
  62510. };
  62511. DracoCompression._LoadScriptAsync = function (url) {
  62512. return new Promise(function (resolve, reject) {
  62513. BABYLON.Tools.LoadScript(url, function () {
  62514. resolve();
  62515. }, function (message) {
  62516. reject(new Error(message));
  62517. });
  62518. });
  62519. };
  62520. DracoCompression._LoadFileAsync = function (url) {
  62521. return new Promise(function (resolve, reject) {
  62522. BABYLON.Tools.LoadFile(url, function (data) {
  62523. resolve(data);
  62524. }, undefined, undefined, true, function (request, exception) {
  62525. reject(exception);
  62526. });
  62527. });
  62528. };
  62529. /**
  62530. * The configuration. Defaults to the following urls:
  62531. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62532. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62533. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62534. */
  62535. DracoCompression.Configuration = {
  62536. decoder: {
  62537. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62538. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62539. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62540. }
  62541. };
  62542. return DracoCompression;
  62543. }());
  62544. BABYLON.DracoCompression = DracoCompression;
  62545. })(BABYLON || (BABYLON = {}));
  62546. //# sourceMappingURL=babylon.dracoCompression.js.map
  62547. var BABYLON;
  62548. (function (BABYLON) {
  62549. var AudioEngine = /** @class */ (function () {
  62550. function AudioEngine() {
  62551. this._audioContext = null;
  62552. this._audioContextInitialized = false;
  62553. this.canUseWebAudio = false;
  62554. this.WarnedWebAudioUnsupported = false;
  62555. this.unlocked = false;
  62556. this.isMP3supported = false;
  62557. this.isOGGsupported = false;
  62558. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62559. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62560. this.canUseWebAudio = true;
  62561. }
  62562. var audioElem = document.createElement('audio');
  62563. try {
  62564. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62565. this.isMP3supported = true;
  62566. }
  62567. }
  62568. catch (e) {
  62569. // protect error during capability check.
  62570. }
  62571. try {
  62572. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62573. this.isOGGsupported = true;
  62574. }
  62575. }
  62576. catch (e) {
  62577. // protect error during capability check.
  62578. }
  62579. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62580. this._unlockiOSaudio();
  62581. }
  62582. else {
  62583. this.unlocked = true;
  62584. }
  62585. }
  62586. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62587. get: function () {
  62588. if (!this._audioContextInitialized) {
  62589. this._initializeAudioContext();
  62590. }
  62591. return this._audioContext;
  62592. },
  62593. enumerable: true,
  62594. configurable: true
  62595. });
  62596. AudioEngine.prototype._unlockiOSaudio = function () {
  62597. var _this = this;
  62598. var unlockaudio = function () {
  62599. if (!_this.audioContext) {
  62600. return;
  62601. }
  62602. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62603. var source = _this.audioContext.createBufferSource();
  62604. source.buffer = buffer;
  62605. source.connect(_this.audioContext.destination);
  62606. source.start(0);
  62607. setTimeout(function () {
  62608. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62609. _this.unlocked = true;
  62610. window.removeEventListener('touchend', unlockaudio, false);
  62611. if (_this.onAudioUnlocked) {
  62612. _this.onAudioUnlocked();
  62613. }
  62614. }
  62615. }, 0);
  62616. };
  62617. window.addEventListener('touchend', unlockaudio, false);
  62618. };
  62619. AudioEngine.prototype._initializeAudioContext = function () {
  62620. try {
  62621. if (this.canUseWebAudio) {
  62622. this._audioContext = new AudioContext();
  62623. // create a global volume gain node
  62624. this.masterGain = this._audioContext.createGain();
  62625. this.masterGain.gain.value = 1;
  62626. this.masterGain.connect(this._audioContext.destination);
  62627. this._audioContextInitialized = true;
  62628. }
  62629. }
  62630. catch (e) {
  62631. this.canUseWebAudio = false;
  62632. BABYLON.Tools.Error("Web Audio: " + e.message);
  62633. }
  62634. };
  62635. AudioEngine.prototype.dispose = function () {
  62636. if (this.canUseWebAudio && this._audioContextInitialized) {
  62637. if (this._connectedAnalyser && this._audioContext) {
  62638. this._connectedAnalyser.stopDebugCanvas();
  62639. this._connectedAnalyser.dispose();
  62640. this.masterGain.disconnect();
  62641. this.masterGain.connect(this._audioContext.destination);
  62642. this._connectedAnalyser = null;
  62643. }
  62644. this.masterGain.gain.value = 1;
  62645. }
  62646. this.WarnedWebAudioUnsupported = false;
  62647. };
  62648. AudioEngine.prototype.getGlobalVolume = function () {
  62649. if (this.canUseWebAudio && this._audioContextInitialized) {
  62650. return this.masterGain.gain.value;
  62651. }
  62652. else {
  62653. return -1;
  62654. }
  62655. };
  62656. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62657. if (this.canUseWebAudio && this._audioContextInitialized) {
  62658. this.masterGain.gain.value = newVolume;
  62659. }
  62660. };
  62661. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62662. if (this._connectedAnalyser) {
  62663. this._connectedAnalyser.stopDebugCanvas();
  62664. }
  62665. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62666. this._connectedAnalyser = analyser;
  62667. this.masterGain.disconnect();
  62668. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62669. }
  62670. };
  62671. return AudioEngine;
  62672. }());
  62673. BABYLON.AudioEngine = AudioEngine;
  62674. })(BABYLON || (BABYLON = {}));
  62675. //# sourceMappingURL=babylon.audioEngine.js.map
  62676. var BABYLON;
  62677. (function (BABYLON) {
  62678. var Sound = /** @class */ (function () {
  62679. /**
  62680. * Create a sound and attach it to a scene
  62681. * @param name Name of your sound
  62682. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62683. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62684. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62685. */
  62686. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62687. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62688. var _this = this;
  62689. this.autoplay = false;
  62690. this.loop = false;
  62691. this.useCustomAttenuation = false;
  62692. this.spatialSound = false;
  62693. this.refDistance = 1;
  62694. this.rolloffFactor = 1;
  62695. this.maxDistance = 100;
  62696. this.distanceModel = "linear";
  62697. this._panningModel = "equalpower";
  62698. this._playbackRate = 1;
  62699. this._streaming = false;
  62700. this._startTime = 0;
  62701. this._startOffset = 0;
  62702. this._position = BABYLON.Vector3.Zero();
  62703. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62704. this._volume = 1;
  62705. this._isReadyToPlay = false;
  62706. this.isPlaying = false;
  62707. this.isPaused = false;
  62708. this._isDirectional = false;
  62709. // Used if you'd like to create a directional sound.
  62710. // If not set, the sound will be omnidirectional
  62711. this._coneInnerAngle = 360;
  62712. this._coneOuterAngle = 360;
  62713. this._coneOuterGain = 0;
  62714. this._isOutputConnected = false;
  62715. this._urlType = "Unknown";
  62716. this.name = name;
  62717. this._scene = scene;
  62718. this._readyToPlayCallback = readyToPlayCallback;
  62719. // Default custom attenuation function is a linear attenuation
  62720. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62721. if (currentDistance < maxDistance) {
  62722. return currentVolume * (1 - currentDistance / maxDistance);
  62723. }
  62724. else {
  62725. return 0;
  62726. }
  62727. };
  62728. if (options) {
  62729. this.autoplay = options.autoplay || false;
  62730. this.loop = options.loop || false;
  62731. // if volume === 0, we need another way to check this option
  62732. if (options.volume !== undefined) {
  62733. this._volume = options.volume;
  62734. }
  62735. this.spatialSound = options.spatialSound || false;
  62736. this.maxDistance = options.maxDistance || 100;
  62737. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62738. this.rolloffFactor = options.rolloffFactor || 1;
  62739. this.refDistance = options.refDistance || 1;
  62740. this.distanceModel = options.distanceModel || "linear";
  62741. this._playbackRate = options.playbackRate || 1;
  62742. this._streaming = options.streaming || false;
  62743. }
  62744. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62745. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62746. this._soundGain.gain.value = this._volume;
  62747. this._inputAudioNode = this._soundGain;
  62748. this._ouputAudioNode = this._soundGain;
  62749. if (this.spatialSound) {
  62750. this._createSpatialParameters();
  62751. }
  62752. this._scene.mainSoundTrack.AddSound(this);
  62753. var validParameter = true;
  62754. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62755. if (urlOrArrayBuffer) {
  62756. try {
  62757. if (typeof (urlOrArrayBuffer) === "string")
  62758. this._urlType = "String";
  62759. if (Array.isArray(urlOrArrayBuffer))
  62760. this._urlType = "Array";
  62761. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62762. this._urlType = "ArrayBuffer";
  62763. var urls = [];
  62764. var codecSupportedFound = false;
  62765. switch (this._urlType) {
  62766. case "ArrayBuffer":
  62767. if (urlOrArrayBuffer.byteLength > 0) {
  62768. codecSupportedFound = true;
  62769. this._soundLoaded(urlOrArrayBuffer);
  62770. }
  62771. break;
  62772. case "String":
  62773. urls.push(urlOrArrayBuffer);
  62774. case "Array":
  62775. if (urls.length === 0)
  62776. urls = urlOrArrayBuffer;
  62777. // If we found a supported format, we load it immediately and stop the loop
  62778. for (var i = 0; i < urls.length; i++) {
  62779. var url = urls[i];
  62780. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62781. codecSupportedFound = true;
  62782. }
  62783. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62784. codecSupportedFound = true;
  62785. }
  62786. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62787. codecSupportedFound = true;
  62788. }
  62789. if (url.indexOf("blob:") !== -1) {
  62790. codecSupportedFound = true;
  62791. }
  62792. if (codecSupportedFound) {
  62793. // Loading sound using XHR2
  62794. if (!this._streaming) {
  62795. this._scene._loadFile(url, function (data) {
  62796. _this._soundLoaded(data);
  62797. }, undefined, true, true, function (exception) {
  62798. if (exception) {
  62799. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62800. }
  62801. BABYLON.Tools.Error("Sound creation aborted.");
  62802. _this._scene.mainSoundTrack.RemoveSound(_this);
  62803. });
  62804. }
  62805. // Streaming sound using HTML5 Audio tag
  62806. else {
  62807. this._htmlAudioElement = new Audio(url);
  62808. this._htmlAudioElement.controls = false;
  62809. this._htmlAudioElement.loop = this.loop;
  62810. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62811. this._htmlAudioElement.preload = "auto";
  62812. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62813. _this._isReadyToPlay = true;
  62814. if (_this.autoplay) {
  62815. _this.play();
  62816. }
  62817. if (_this._readyToPlayCallback) {
  62818. _this._readyToPlayCallback();
  62819. }
  62820. });
  62821. document.body.appendChild(this._htmlAudioElement);
  62822. }
  62823. break;
  62824. }
  62825. }
  62826. break;
  62827. default:
  62828. validParameter = false;
  62829. break;
  62830. }
  62831. if (!validParameter) {
  62832. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62833. }
  62834. else {
  62835. if (!codecSupportedFound) {
  62836. this._isReadyToPlay = true;
  62837. // Simulating a ready to play event to avoid breaking code path
  62838. if (this._readyToPlayCallback) {
  62839. window.setTimeout(function () {
  62840. if (_this._readyToPlayCallback) {
  62841. _this._readyToPlayCallback();
  62842. }
  62843. }, 1000);
  62844. }
  62845. }
  62846. }
  62847. }
  62848. catch (ex) {
  62849. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62850. this._scene.mainSoundTrack.RemoveSound(this);
  62851. }
  62852. }
  62853. }
  62854. else {
  62855. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62856. this._scene.mainSoundTrack.AddSound(this);
  62857. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62858. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62859. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62860. }
  62861. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62862. if (this._readyToPlayCallback) {
  62863. window.setTimeout(function () {
  62864. if (_this._readyToPlayCallback) {
  62865. _this._readyToPlayCallback();
  62866. }
  62867. }, 1000);
  62868. }
  62869. }
  62870. }
  62871. Sound.prototype.dispose = function () {
  62872. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62873. if (this.isPlaying) {
  62874. this.stop();
  62875. }
  62876. this._isReadyToPlay = false;
  62877. if (this.soundTrackId === -1) {
  62878. this._scene.mainSoundTrack.RemoveSound(this);
  62879. }
  62880. else {
  62881. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62882. }
  62883. if (this._soundGain) {
  62884. this._soundGain.disconnect();
  62885. this._soundGain = null;
  62886. }
  62887. if (this._soundPanner) {
  62888. this._soundPanner.disconnect();
  62889. this._soundPanner = null;
  62890. }
  62891. if (this._soundSource) {
  62892. this._soundSource.disconnect();
  62893. this._soundSource = null;
  62894. }
  62895. this._audioBuffer = null;
  62896. if (this._htmlAudioElement) {
  62897. this._htmlAudioElement.pause();
  62898. this._htmlAudioElement.src = "";
  62899. document.body.removeChild(this._htmlAudioElement);
  62900. }
  62901. if (this._connectedMesh && this._registerFunc) {
  62902. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62903. this._connectedMesh = null;
  62904. }
  62905. }
  62906. };
  62907. Sound.prototype.isReady = function () {
  62908. return this._isReadyToPlay;
  62909. };
  62910. Sound.prototype._soundLoaded = function (audioData) {
  62911. var _this = this;
  62912. if (!BABYLON.Engine.audioEngine.audioContext) {
  62913. return;
  62914. }
  62915. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62916. _this._audioBuffer = buffer;
  62917. _this._isReadyToPlay = true;
  62918. if (_this.autoplay) {
  62919. _this.play();
  62920. }
  62921. if (_this._readyToPlayCallback) {
  62922. _this._readyToPlayCallback();
  62923. }
  62924. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62925. };
  62926. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62927. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62928. this._audioBuffer = audioBuffer;
  62929. this._isReadyToPlay = true;
  62930. }
  62931. };
  62932. Sound.prototype.updateOptions = function (options) {
  62933. if (options) {
  62934. this.loop = options.loop || this.loop;
  62935. this.maxDistance = options.maxDistance || this.maxDistance;
  62936. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62937. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62938. this.refDistance = options.refDistance || this.refDistance;
  62939. this.distanceModel = options.distanceModel || this.distanceModel;
  62940. this._playbackRate = options.playbackRate || this._playbackRate;
  62941. this._updateSpatialParameters();
  62942. if (this.isPlaying) {
  62943. if (this._streaming) {
  62944. this._htmlAudioElement.playbackRate = this._playbackRate;
  62945. }
  62946. else {
  62947. if (this._soundSource) {
  62948. this._soundSource.playbackRate.value = this._playbackRate;
  62949. }
  62950. }
  62951. }
  62952. }
  62953. };
  62954. Sound.prototype._createSpatialParameters = function () {
  62955. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62956. if (this._scene.headphone) {
  62957. this._panningModel = "HRTF";
  62958. }
  62959. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62960. this._updateSpatialParameters();
  62961. this._soundPanner.connect(this._ouputAudioNode);
  62962. this._inputAudioNode = this._soundPanner;
  62963. }
  62964. };
  62965. Sound.prototype._updateSpatialParameters = function () {
  62966. if (this.spatialSound && this._soundPanner) {
  62967. if (this.useCustomAttenuation) {
  62968. // Tricks to disable in a way embedded Web Audio attenuation
  62969. this._soundPanner.distanceModel = "linear";
  62970. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62971. this._soundPanner.refDistance = 1;
  62972. this._soundPanner.rolloffFactor = 1;
  62973. this._soundPanner.panningModel = this._panningModel;
  62974. }
  62975. else {
  62976. this._soundPanner.distanceModel = this.distanceModel;
  62977. this._soundPanner.maxDistance = this.maxDistance;
  62978. this._soundPanner.refDistance = this.refDistance;
  62979. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62980. this._soundPanner.panningModel = this._panningModel;
  62981. }
  62982. }
  62983. };
  62984. Sound.prototype.switchPanningModelToHRTF = function () {
  62985. this._panningModel = "HRTF";
  62986. this._switchPanningModel();
  62987. };
  62988. Sound.prototype.switchPanningModelToEqualPower = function () {
  62989. this._panningModel = "equalpower";
  62990. this._switchPanningModel();
  62991. };
  62992. Sound.prototype._switchPanningModel = function () {
  62993. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62994. this._soundPanner.panningModel = this._panningModel;
  62995. }
  62996. };
  62997. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62998. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62999. if (this._isOutputConnected) {
  63000. this._ouputAudioNode.disconnect();
  63001. }
  63002. this._ouputAudioNode.connect(soundTrackAudioNode);
  63003. this._isOutputConnected = true;
  63004. }
  63005. };
  63006. /**
  63007. * Transform this sound into a directional source
  63008. * @param coneInnerAngle Size of the inner cone in degree
  63009. * @param coneOuterAngle Size of the outer cone in degree
  63010. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63011. */
  63012. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63013. if (coneOuterAngle < coneInnerAngle) {
  63014. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63015. return;
  63016. }
  63017. this._coneInnerAngle = coneInnerAngle;
  63018. this._coneOuterAngle = coneOuterAngle;
  63019. this._coneOuterGain = coneOuterGain;
  63020. this._isDirectional = true;
  63021. if (this.isPlaying && this.loop) {
  63022. this.stop();
  63023. this.play();
  63024. }
  63025. };
  63026. Sound.prototype.setPosition = function (newPosition) {
  63027. this._position = newPosition;
  63028. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63029. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63030. }
  63031. };
  63032. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63033. this._localDirection = newLocalDirection;
  63034. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63035. this._updateDirection();
  63036. }
  63037. };
  63038. Sound.prototype._updateDirection = function () {
  63039. if (!this._connectedMesh || !this._soundPanner) {
  63040. return;
  63041. }
  63042. var mat = this._connectedMesh.getWorldMatrix();
  63043. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63044. direction.normalize();
  63045. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63046. };
  63047. Sound.prototype.updateDistanceFromListener = function () {
  63048. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63049. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63050. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63051. }
  63052. };
  63053. Sound.prototype.setAttenuationFunction = function (callback) {
  63054. this._customAttenuationFunction = callback;
  63055. };
  63056. /**
  63057. * Play the sound
  63058. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63059. * @param offset (optional) Start the sound setting it at a specific time
  63060. */
  63061. Sound.prototype.play = function (time, offset) {
  63062. var _this = this;
  63063. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63064. try {
  63065. if (this._startOffset < 0) {
  63066. time = -this._startOffset;
  63067. this._startOffset = 0;
  63068. }
  63069. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63070. if (!this._soundSource || !this._streamingSource) {
  63071. if (this.spatialSound && this._soundPanner) {
  63072. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63073. if (this._isDirectional) {
  63074. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63075. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63076. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63077. if (this._connectedMesh) {
  63078. this._updateDirection();
  63079. }
  63080. else {
  63081. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63082. }
  63083. }
  63084. }
  63085. }
  63086. if (this._streaming) {
  63087. if (!this._streamingSource) {
  63088. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63089. this._htmlAudioElement.onended = function () { _this._onended(); };
  63090. this._htmlAudioElement.playbackRate = this._playbackRate;
  63091. }
  63092. this._streamingSource.disconnect();
  63093. this._streamingSource.connect(this._inputAudioNode);
  63094. this._htmlAudioElement.play();
  63095. }
  63096. else {
  63097. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63098. this._soundSource.buffer = this._audioBuffer;
  63099. this._soundSource.connect(this._inputAudioNode);
  63100. this._soundSource.loop = this.loop;
  63101. this._soundSource.playbackRate.value = this._playbackRate;
  63102. this._soundSource.onended = function () { _this._onended(); };
  63103. if (this._soundSource.buffer) {
  63104. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63105. }
  63106. }
  63107. this._startTime = startTime;
  63108. this.isPlaying = true;
  63109. this.isPaused = false;
  63110. }
  63111. catch (ex) {
  63112. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63113. }
  63114. }
  63115. };
  63116. Sound.prototype._onended = function () {
  63117. this.isPlaying = false;
  63118. if (this.onended) {
  63119. this.onended();
  63120. }
  63121. };
  63122. /**
  63123. * Stop the sound
  63124. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63125. */
  63126. Sound.prototype.stop = function (time) {
  63127. if (this.isPlaying) {
  63128. if (this._streaming) {
  63129. this._htmlAudioElement.pause();
  63130. // Test needed for Firefox or it will generate an Invalid State Error
  63131. if (this._htmlAudioElement.currentTime > 0) {
  63132. this._htmlAudioElement.currentTime = 0;
  63133. }
  63134. }
  63135. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63136. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63137. this._soundSource.stop(stopTime);
  63138. this._soundSource.onended = function () { };
  63139. if (!this.isPaused) {
  63140. this._startOffset = 0;
  63141. }
  63142. }
  63143. this.isPlaying = false;
  63144. }
  63145. };
  63146. Sound.prototype.pause = function () {
  63147. if (this.isPlaying) {
  63148. this.isPaused = true;
  63149. if (this._streaming) {
  63150. this._htmlAudioElement.pause();
  63151. }
  63152. else if (BABYLON.Engine.audioEngine.audioContext) {
  63153. this.stop(0);
  63154. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63155. }
  63156. }
  63157. };
  63158. Sound.prototype.setVolume = function (newVolume, time) {
  63159. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63160. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63161. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63162. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63163. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63164. }
  63165. else {
  63166. this._soundGain.gain.value = newVolume;
  63167. }
  63168. }
  63169. this._volume = newVolume;
  63170. };
  63171. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63172. this._playbackRate = newPlaybackRate;
  63173. if (this.isPlaying) {
  63174. if (this._streaming) {
  63175. this._htmlAudioElement.playbackRate = this._playbackRate;
  63176. }
  63177. else if (this._soundSource) {
  63178. this._soundSource.playbackRate.value = this._playbackRate;
  63179. }
  63180. }
  63181. };
  63182. Sound.prototype.getVolume = function () {
  63183. return this._volume;
  63184. };
  63185. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63186. var _this = this;
  63187. if (this._connectedMesh && this._registerFunc) {
  63188. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63189. this._registerFunc = null;
  63190. }
  63191. this._connectedMesh = meshToConnectTo;
  63192. if (!this.spatialSound) {
  63193. this.spatialSound = true;
  63194. this._createSpatialParameters();
  63195. if (this.isPlaying && this.loop) {
  63196. this.stop();
  63197. this.play();
  63198. }
  63199. }
  63200. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63201. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63202. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63203. };
  63204. Sound.prototype.detachFromMesh = function () {
  63205. if (this._connectedMesh && this._registerFunc) {
  63206. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63207. this._registerFunc = null;
  63208. this._connectedMesh = null;
  63209. }
  63210. };
  63211. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63212. if (!node.getBoundingInfo) {
  63213. return;
  63214. }
  63215. var mesh = node;
  63216. var boundingInfo = mesh.getBoundingInfo();
  63217. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63218. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63219. this._updateDirection();
  63220. }
  63221. };
  63222. Sound.prototype.clone = function () {
  63223. var _this = this;
  63224. if (!this._streaming) {
  63225. var setBufferAndRun = function () {
  63226. if (_this._isReadyToPlay) {
  63227. clonedSound._audioBuffer = _this.getAudioBuffer();
  63228. clonedSound._isReadyToPlay = true;
  63229. if (clonedSound.autoplay) {
  63230. clonedSound.play();
  63231. }
  63232. }
  63233. else {
  63234. window.setTimeout(setBufferAndRun, 300);
  63235. }
  63236. };
  63237. var currentOptions = {
  63238. autoplay: this.autoplay, loop: this.loop,
  63239. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63240. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63241. refDistance: this.refDistance, distanceModel: this.distanceModel
  63242. };
  63243. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63244. if (this.useCustomAttenuation) {
  63245. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63246. }
  63247. clonedSound.setPosition(this._position);
  63248. clonedSound.setPlaybackRate(this._playbackRate);
  63249. setBufferAndRun();
  63250. return clonedSound;
  63251. }
  63252. // Can't clone a streaming sound
  63253. else {
  63254. return null;
  63255. }
  63256. };
  63257. Sound.prototype.getAudioBuffer = function () {
  63258. return this._audioBuffer;
  63259. };
  63260. Sound.prototype.serialize = function () {
  63261. var serializationObject = {
  63262. name: this.name,
  63263. url: this.name,
  63264. autoplay: this.autoplay,
  63265. loop: this.loop,
  63266. volume: this._volume,
  63267. spatialSound: this.spatialSound,
  63268. maxDistance: this.maxDistance,
  63269. rolloffFactor: this.rolloffFactor,
  63270. refDistance: this.refDistance,
  63271. distanceModel: this.distanceModel,
  63272. playbackRate: this._playbackRate,
  63273. panningModel: this._panningModel,
  63274. soundTrackId: this.soundTrackId
  63275. };
  63276. if (this.spatialSound) {
  63277. if (this._connectedMesh)
  63278. serializationObject.connectedMeshId = this._connectedMesh.id;
  63279. serializationObject.position = this._position.asArray();
  63280. serializationObject.refDistance = this.refDistance;
  63281. serializationObject.distanceModel = this.distanceModel;
  63282. serializationObject.isDirectional = this._isDirectional;
  63283. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63284. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63285. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63286. serializationObject.coneOuterGain = this._coneOuterGain;
  63287. }
  63288. return serializationObject;
  63289. };
  63290. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63291. var soundName = parsedSound.name;
  63292. var soundUrl;
  63293. if (parsedSound.url) {
  63294. soundUrl = rootUrl + parsedSound.url;
  63295. }
  63296. else {
  63297. soundUrl = rootUrl + soundName;
  63298. }
  63299. var options = {
  63300. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63301. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63302. rolloffFactor: parsedSound.rolloffFactor,
  63303. refDistance: parsedSound.refDistance,
  63304. distanceModel: parsedSound.distanceModel,
  63305. playbackRate: parsedSound.playbackRate
  63306. };
  63307. var newSound;
  63308. if (!sourceSound) {
  63309. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63310. scene._addPendingData(newSound);
  63311. }
  63312. else {
  63313. var setBufferAndRun = function () {
  63314. if (sourceSound._isReadyToPlay) {
  63315. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63316. newSound._isReadyToPlay = true;
  63317. if (newSound.autoplay) {
  63318. newSound.play();
  63319. }
  63320. }
  63321. else {
  63322. window.setTimeout(setBufferAndRun, 300);
  63323. }
  63324. };
  63325. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63326. setBufferAndRun();
  63327. }
  63328. if (parsedSound.position) {
  63329. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63330. newSound.setPosition(soundPosition);
  63331. }
  63332. if (parsedSound.isDirectional) {
  63333. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63334. if (parsedSound.localDirectionToMesh) {
  63335. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63336. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63337. }
  63338. }
  63339. if (parsedSound.connectedMeshId) {
  63340. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63341. if (connectedMesh) {
  63342. newSound.attachToMesh(connectedMesh);
  63343. }
  63344. }
  63345. return newSound;
  63346. };
  63347. return Sound;
  63348. }());
  63349. BABYLON.Sound = Sound;
  63350. })(BABYLON || (BABYLON = {}));
  63351. //# sourceMappingURL=babylon.sound.js.map
  63352. var BABYLON;
  63353. (function (BABYLON) {
  63354. var SoundTrack = /** @class */ (function () {
  63355. function SoundTrack(scene, options) {
  63356. this.id = -1;
  63357. this._isMainTrack = false;
  63358. this._isInitialized = false;
  63359. this._scene = scene;
  63360. this.soundCollection = new Array();
  63361. this._options = options;
  63362. if (!this._isMainTrack) {
  63363. this._scene.soundTracks.push(this);
  63364. this.id = this._scene.soundTracks.length - 1;
  63365. }
  63366. }
  63367. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63368. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63369. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63370. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63371. if (this._options) {
  63372. if (this._options.volume) {
  63373. this._outputAudioNode.gain.value = this._options.volume;
  63374. }
  63375. if (this._options.mainTrack) {
  63376. this._isMainTrack = this._options.mainTrack;
  63377. }
  63378. }
  63379. this._isInitialized = true;
  63380. }
  63381. };
  63382. SoundTrack.prototype.dispose = function () {
  63383. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63384. if (this._connectedAnalyser) {
  63385. this._connectedAnalyser.stopDebugCanvas();
  63386. }
  63387. while (this.soundCollection.length) {
  63388. this.soundCollection[0].dispose();
  63389. }
  63390. if (this._outputAudioNode) {
  63391. this._outputAudioNode.disconnect();
  63392. }
  63393. this._outputAudioNode = null;
  63394. }
  63395. };
  63396. SoundTrack.prototype.AddSound = function (sound) {
  63397. if (!this._isInitialized) {
  63398. this._initializeSoundTrackAudioGraph();
  63399. }
  63400. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63401. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63402. }
  63403. if (sound.soundTrackId) {
  63404. if (sound.soundTrackId === -1) {
  63405. this._scene.mainSoundTrack.RemoveSound(sound);
  63406. }
  63407. else {
  63408. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63409. }
  63410. }
  63411. this.soundCollection.push(sound);
  63412. sound.soundTrackId = this.id;
  63413. };
  63414. SoundTrack.prototype.RemoveSound = function (sound) {
  63415. var index = this.soundCollection.indexOf(sound);
  63416. if (index !== -1) {
  63417. this.soundCollection.splice(index, 1);
  63418. }
  63419. };
  63420. SoundTrack.prototype.setVolume = function (newVolume) {
  63421. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63422. this._outputAudioNode.gain.value = newVolume;
  63423. }
  63424. };
  63425. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63426. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63427. for (var i = 0; i < this.soundCollection.length; i++) {
  63428. this.soundCollection[i].switchPanningModelToHRTF();
  63429. }
  63430. }
  63431. };
  63432. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63433. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63434. for (var i = 0; i < this.soundCollection.length; i++) {
  63435. this.soundCollection[i].switchPanningModelToEqualPower();
  63436. }
  63437. }
  63438. };
  63439. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63440. if (this._connectedAnalyser) {
  63441. this._connectedAnalyser.stopDebugCanvas();
  63442. }
  63443. this._connectedAnalyser = analyser;
  63444. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63445. this._outputAudioNode.disconnect();
  63446. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63447. }
  63448. };
  63449. return SoundTrack;
  63450. }());
  63451. BABYLON.SoundTrack = SoundTrack;
  63452. })(BABYLON || (BABYLON = {}));
  63453. //# sourceMappingURL=babylon.soundtrack.js.map
  63454. var BABYLON;
  63455. (function (BABYLON) {
  63456. /**
  63457. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63458. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63459. */
  63460. var Analyser = /** @class */ (function () {
  63461. /**
  63462. * Creates a new analyser
  63463. * @param scene defines hosting scene
  63464. */
  63465. function Analyser(scene) {
  63466. /**
  63467. * Gets or sets the smoothing
  63468. * @ignorenaming
  63469. */
  63470. this.SMOOTHING = 0.75;
  63471. /**
  63472. * Gets or sets the FFT table size
  63473. * @ignorenaming
  63474. */
  63475. this.FFT_SIZE = 512;
  63476. /**
  63477. * Gets or sets the bar graph amplitude
  63478. * @ignorenaming
  63479. */
  63480. this.BARGRAPHAMPLITUDE = 256;
  63481. /**
  63482. * Gets or sets the position of the debug canvas
  63483. * @ignorenaming
  63484. */
  63485. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63486. /**
  63487. * Gets or sets the debug canvas size
  63488. * @ignorenaming
  63489. */
  63490. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63491. this._scene = scene;
  63492. this._audioEngine = BABYLON.Engine.audioEngine;
  63493. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63494. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63495. this._webAudioAnalyser.minDecibels = -140;
  63496. this._webAudioAnalyser.maxDecibels = 0;
  63497. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63498. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63499. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63500. }
  63501. }
  63502. /**
  63503. * Get the number of data values you will have to play with for the visualization
  63504. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63505. * @returns a number
  63506. */
  63507. Analyser.prototype.getFrequencyBinCount = function () {
  63508. if (this._audioEngine.canUseWebAudio) {
  63509. return this._webAudioAnalyser.frequencyBinCount;
  63510. }
  63511. else {
  63512. return 0;
  63513. }
  63514. };
  63515. /**
  63516. * Gets the current frequency data as a byte array
  63517. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63518. * @returns a Uint8Array
  63519. */
  63520. Analyser.prototype.getByteFrequencyData = function () {
  63521. if (this._audioEngine.canUseWebAudio) {
  63522. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63523. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63524. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63525. }
  63526. return this._byteFreqs;
  63527. };
  63528. /**
  63529. * Gets the current waveform as a byte array
  63530. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63531. * @returns a Uint8Array
  63532. */
  63533. Analyser.prototype.getByteTimeDomainData = function () {
  63534. if (this._audioEngine.canUseWebAudio) {
  63535. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63536. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63537. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63538. }
  63539. return this._byteTime;
  63540. };
  63541. /**
  63542. * Gets the current frequency data as a float array
  63543. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63544. * @returns a Float32Array
  63545. */
  63546. Analyser.prototype.getFloatFrequencyData = function () {
  63547. if (this._audioEngine.canUseWebAudio) {
  63548. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63549. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63550. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63551. }
  63552. return this._floatFreqs;
  63553. };
  63554. /**
  63555. * Renders the debug canvas
  63556. */
  63557. Analyser.prototype.drawDebugCanvas = function () {
  63558. var _this = this;
  63559. if (this._audioEngine.canUseWebAudio) {
  63560. if (!this._debugCanvas) {
  63561. this._debugCanvas = document.createElement("canvas");
  63562. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63563. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63564. this._debugCanvas.style.position = "absolute";
  63565. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63566. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63567. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63568. document.body.appendChild(this._debugCanvas);
  63569. this._registerFunc = function () {
  63570. _this.drawDebugCanvas();
  63571. };
  63572. this._scene.registerBeforeRender(this._registerFunc);
  63573. }
  63574. if (this._registerFunc && this._debugCanvasContext) {
  63575. var workingArray = this.getByteFrequencyData();
  63576. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63577. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63578. // Draw the frequency domain chart.
  63579. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63580. var value = workingArray[i];
  63581. var percent = value / this.BARGRAPHAMPLITUDE;
  63582. var height = this.DEBUGCANVASSIZE.height * percent;
  63583. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63584. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63585. var hue = i / this.getFrequencyBinCount() * 360;
  63586. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63587. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63588. }
  63589. }
  63590. }
  63591. };
  63592. /**
  63593. * Stops rendering the debug canvas and removes it
  63594. */
  63595. Analyser.prototype.stopDebugCanvas = function () {
  63596. if (this._debugCanvas) {
  63597. if (this._registerFunc) {
  63598. this._scene.unregisterBeforeRender(this._registerFunc);
  63599. this._registerFunc = null;
  63600. }
  63601. document.body.removeChild(this._debugCanvas);
  63602. this._debugCanvas = null;
  63603. this._debugCanvasContext = null;
  63604. }
  63605. };
  63606. /**
  63607. * Connects two audio nodes
  63608. * @param inputAudioNode defines first node to connect
  63609. * @param outputAudioNode defines second node to connect
  63610. */
  63611. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63612. if (this._audioEngine.canUseWebAudio) {
  63613. inputAudioNode.connect(this._webAudioAnalyser);
  63614. this._webAudioAnalyser.connect(outputAudioNode);
  63615. }
  63616. };
  63617. /**
  63618. * Releases all associated resources
  63619. */
  63620. Analyser.prototype.dispose = function () {
  63621. if (this._audioEngine.canUseWebAudio) {
  63622. this._webAudioAnalyser.disconnect();
  63623. }
  63624. };
  63625. return Analyser;
  63626. }());
  63627. BABYLON.Analyser = Analyser;
  63628. })(BABYLON || (BABYLON = {}));
  63629. //# sourceMappingURL=babylon.analyser.js.map
  63630. var BABYLON;
  63631. (function (BABYLON) {
  63632. var CubeTexture = /** @class */ (function (_super) {
  63633. __extends(CubeTexture, _super);
  63634. /**
  63635. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63636. * as prefiltered data.
  63637. * @param rootUrl defines the url of the texture or the root name of the six images
  63638. * @param scene defines the scene the texture is attached to
  63639. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63640. * @param noMipmap defines if mipmaps should be created or not
  63641. * @param files defines the six files to load for the different faces
  63642. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63643. * @param onError defines a callback triggered in case of error during load
  63644. * @param format defines the internal format to use for the texture once loaded
  63645. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63646. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63647. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63648. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63649. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63650. * @return the cube texture
  63651. */
  63652. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63653. if (extensions === void 0) { extensions = null; }
  63654. if (noMipmap === void 0) { noMipmap = false; }
  63655. if (files === void 0) { files = null; }
  63656. if (onLoad === void 0) { onLoad = null; }
  63657. if (onError === void 0) { onError = null; }
  63658. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63659. if (prefiltered === void 0) { prefiltered = false; }
  63660. if (forcedExtension === void 0) { forcedExtension = null; }
  63661. if (createPolynomials === void 0) { createPolynomials = false; }
  63662. if (lodScale === void 0) { lodScale = 0.8; }
  63663. if (lodOffset === void 0) { lodOffset = 0; }
  63664. var _this = _super.call(this, scene) || this;
  63665. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63666. /**
  63667. * Gets or sets the center of the bounding box associated with the cube texture
  63668. * It must define where the camera used to render the texture was set
  63669. */
  63670. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63671. _this._rotationY = 0;
  63672. /** @hidden */
  63673. _this._prefiltered = false;
  63674. _this.name = rootUrl;
  63675. _this.url = rootUrl;
  63676. _this._noMipmap = noMipmap;
  63677. _this.hasAlpha = false;
  63678. _this._format = format;
  63679. _this._prefiltered = prefiltered;
  63680. _this.isCube = true;
  63681. _this._textureMatrix = BABYLON.Matrix.Identity();
  63682. _this._createPolynomials = createPolynomials;
  63683. if (prefiltered) {
  63684. _this.gammaSpace = false;
  63685. }
  63686. if (!rootUrl && !files) {
  63687. return _this;
  63688. }
  63689. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63690. var lastDot = rootUrl.lastIndexOf(".");
  63691. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63692. var isDDS = (extension === ".dds");
  63693. var isEnv = (extension === ".env");
  63694. if (isEnv) {
  63695. _this.gammaSpace = false;
  63696. }
  63697. if (!files) {
  63698. if (!isEnv && !isDDS && !extensions) {
  63699. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63700. }
  63701. files = [];
  63702. if (extensions) {
  63703. for (var index = 0; index < extensions.length; index++) {
  63704. files.push(rootUrl + extensions[index]);
  63705. }
  63706. }
  63707. }
  63708. _this._files = files;
  63709. if (!_this._texture) {
  63710. if (!scene.useDelayedTextureLoading) {
  63711. if (prefiltered) {
  63712. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63713. }
  63714. else {
  63715. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63716. }
  63717. }
  63718. else {
  63719. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63720. }
  63721. }
  63722. else if (onLoad) {
  63723. if (_this._texture.isReady) {
  63724. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63725. }
  63726. else {
  63727. _this._texture.onLoadedObservable.add(onLoad);
  63728. }
  63729. }
  63730. return _this;
  63731. }
  63732. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63733. get: function () {
  63734. return this._boundingBoxSize;
  63735. },
  63736. /**
  63737. * Gets or sets the size of the bounding box associated with the cube texture
  63738. * When defined, the cubemap will switch to local mode
  63739. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63740. * @example https://www.babylonjs-playground.com/#RNASML
  63741. */
  63742. set: function (value) {
  63743. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63744. return;
  63745. }
  63746. this._boundingBoxSize = value;
  63747. var scene = this.getScene();
  63748. if (scene) {
  63749. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63750. }
  63751. },
  63752. enumerable: true,
  63753. configurable: true
  63754. });
  63755. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63756. /**
  63757. * Gets texture matrix rotation angle around Y axis radians.
  63758. */
  63759. get: function () {
  63760. return this._rotationY;
  63761. },
  63762. /**
  63763. * Sets texture matrix rotation angle around Y axis in radians.
  63764. */
  63765. set: function (value) {
  63766. this._rotationY = value;
  63767. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63768. },
  63769. enumerable: true,
  63770. configurable: true
  63771. });
  63772. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63773. var rootUrlKey = "";
  63774. files.forEach(function (url) { return rootUrlKey += url; });
  63775. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63776. };
  63777. /**
  63778. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63779. * @param url defines the url of the prefiltered texture
  63780. * @param scene defines the scene the texture is attached to
  63781. * @param forcedExtension defines the extension of the file if different from the url
  63782. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63783. * @return the prefiltered texture
  63784. */
  63785. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63786. if (forcedExtension === void 0) { forcedExtension = null; }
  63787. if (createPolynomials === void 0) { createPolynomials = true; }
  63788. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63789. };
  63790. // Methods
  63791. CubeTexture.prototype.delayLoad = function () {
  63792. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63793. return;
  63794. }
  63795. var scene = this.getScene();
  63796. if (!scene) {
  63797. return;
  63798. }
  63799. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63800. this._texture = this._getFromCache(this.url, this._noMipmap);
  63801. if (!this._texture) {
  63802. if (this._prefiltered) {
  63803. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63804. }
  63805. else {
  63806. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63807. }
  63808. }
  63809. };
  63810. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63811. return this._textureMatrix;
  63812. };
  63813. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63814. this._textureMatrix = value;
  63815. };
  63816. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63817. var texture = BABYLON.SerializationHelper.Parse(function () {
  63818. var prefiltered = false;
  63819. if (parsedTexture.prefiltered) {
  63820. prefiltered = parsedTexture.prefiltered;
  63821. }
  63822. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63823. }, parsedTexture, scene);
  63824. // Local Cubemaps
  63825. if (parsedTexture.boundingBoxPosition) {
  63826. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63827. }
  63828. if (parsedTexture.boundingBoxSize) {
  63829. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63830. }
  63831. // Animations
  63832. if (parsedTexture.animations) {
  63833. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63834. var parsedAnimation = parsedTexture.animations[animationIndex];
  63835. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63836. }
  63837. }
  63838. return texture;
  63839. };
  63840. CubeTexture.prototype.clone = function () {
  63841. var _this = this;
  63842. return BABYLON.SerializationHelper.Clone(function () {
  63843. var scene = _this.getScene();
  63844. if (!scene) {
  63845. return _this;
  63846. }
  63847. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63848. }, this);
  63849. };
  63850. __decorate([
  63851. BABYLON.serialize("rotationY")
  63852. ], CubeTexture.prototype, "_rotationY", void 0);
  63853. return CubeTexture;
  63854. }(BABYLON.BaseTexture));
  63855. BABYLON.CubeTexture = CubeTexture;
  63856. })(BABYLON || (BABYLON = {}));
  63857. //# sourceMappingURL=babylon.cubeTexture.js.map
  63858. var BABYLON;
  63859. (function (BABYLON) {
  63860. var RenderTargetTexture = /** @class */ (function (_super) {
  63861. __extends(RenderTargetTexture, _super);
  63862. /**
  63863. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63864. * or used a shadow, depth texture...
  63865. * @param name The friendly name of the texture
  63866. * @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)
  63867. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63868. * @param generateMipMaps True if mip maps need to be generated after render.
  63869. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63870. * @param type The type of the buffer in the RTT (int, half float, float...)
  63871. * @param isCube True if a cube texture needs to be created
  63872. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63873. * @param generateDepthBuffer True to generate a depth buffer
  63874. * @param generateStencilBuffer True to generate a stencil buffer
  63875. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63876. */
  63877. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63878. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63879. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63880. if (isCube === void 0) { isCube = false; }
  63881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63882. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63883. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63884. if (isMulti === void 0) { isMulti = false; }
  63885. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63886. _this.isCube = isCube;
  63887. /**
  63888. * Use this list to define the list of mesh you want to render.
  63889. */
  63890. _this.renderList = new Array();
  63891. _this.renderParticles = true;
  63892. _this.renderSprites = false;
  63893. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63894. _this.ignoreCameraViewport = false;
  63895. // Events
  63896. /**
  63897. * An event triggered when the texture is unbind.
  63898. */
  63899. _this.onBeforeBindObservable = new BABYLON.Observable();
  63900. /**
  63901. * An event triggered when the texture is unbind.
  63902. */
  63903. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63904. /**
  63905. * An event triggered before rendering the texture
  63906. */
  63907. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63908. /**
  63909. * An event triggered after rendering the texture
  63910. */
  63911. _this.onAfterRenderObservable = new BABYLON.Observable();
  63912. /**
  63913. * An event triggered after the texture clear
  63914. */
  63915. _this.onClearObservable = new BABYLON.Observable();
  63916. _this._currentRefreshId = -1;
  63917. _this._refreshRate = 1;
  63918. _this._samples = 1;
  63919. /**
  63920. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63921. * It must define where the camera used to render the texture is set
  63922. */
  63923. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63924. scene = _this.getScene();
  63925. if (!scene) {
  63926. return _this;
  63927. }
  63928. _this._engine = scene.getEngine();
  63929. _this.name = name;
  63930. _this.isRenderTarget = true;
  63931. _this._initialSizeParameter = size;
  63932. _this._processSizeParameter(size);
  63933. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63934. });
  63935. _this._generateMipMaps = generateMipMaps ? true : false;
  63936. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63937. // Rendering groups
  63938. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63939. if (isMulti) {
  63940. return _this;
  63941. }
  63942. _this._renderTargetOptions = {
  63943. generateMipMaps: generateMipMaps,
  63944. type: type,
  63945. samplingMode: samplingMode,
  63946. generateDepthBuffer: generateDepthBuffer,
  63947. generateStencilBuffer: generateStencilBuffer
  63948. };
  63949. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63950. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63951. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63952. }
  63953. if (isCube) {
  63954. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63955. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63956. _this._textureMatrix = BABYLON.Matrix.Identity();
  63957. }
  63958. else {
  63959. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63960. }
  63961. return _this;
  63962. }
  63963. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63964. get: function () {
  63965. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63966. },
  63967. enumerable: true,
  63968. configurable: true
  63969. });
  63970. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63971. get: function () {
  63972. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63973. },
  63974. enumerable: true,
  63975. configurable: true
  63976. });
  63977. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63978. get: function () {
  63979. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63980. },
  63981. enumerable: true,
  63982. configurable: true
  63983. });
  63984. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63985. set: function (callback) {
  63986. if (this._onAfterUnbindObserver) {
  63987. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63988. }
  63989. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63995. set: function (callback) {
  63996. if (this._onBeforeRenderObserver) {
  63997. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63998. }
  63999. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64000. },
  64001. enumerable: true,
  64002. configurable: true
  64003. });
  64004. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64005. set: function (callback) {
  64006. if (this._onAfterRenderObserver) {
  64007. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64008. }
  64009. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64010. },
  64011. enumerable: true,
  64012. configurable: true
  64013. });
  64014. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64015. set: function (callback) {
  64016. if (this._onClearObserver) {
  64017. this.onClearObservable.remove(this._onClearObserver);
  64018. }
  64019. this._onClearObserver = this.onClearObservable.add(callback);
  64020. },
  64021. enumerable: true,
  64022. configurable: true
  64023. });
  64024. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64025. get: function () {
  64026. return this._renderTargetOptions;
  64027. },
  64028. enumerable: true,
  64029. configurable: true
  64030. });
  64031. RenderTargetTexture.prototype._onRatioRescale = function () {
  64032. if (this._sizeRatio) {
  64033. this.resize(this._initialSizeParameter);
  64034. }
  64035. };
  64036. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64037. get: function () {
  64038. return this._boundingBoxSize;
  64039. },
  64040. /**
  64041. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64042. * When defined, the cubemap will switch to local mode
  64043. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64044. * @example https://www.babylonjs-playground.com/#RNASML
  64045. */
  64046. set: function (value) {
  64047. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64048. return;
  64049. }
  64050. this._boundingBoxSize = value;
  64051. var scene = this.getScene();
  64052. if (scene) {
  64053. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64054. }
  64055. },
  64056. enumerable: true,
  64057. configurable: true
  64058. });
  64059. /**
  64060. * Creates a depth stencil texture.
  64061. * This is only available in WebGL 2 or with the depth texture extension available.
  64062. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64063. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64064. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64065. */
  64066. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64067. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64068. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64069. if (generateStencil === void 0) { generateStencil = false; }
  64070. if (!this.getScene()) {
  64071. return;
  64072. }
  64073. var engine = this.getScene().getEngine();
  64074. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64075. bilinearFiltering: bilinearFiltering,
  64076. comparisonFunction: comparisonFunction,
  64077. generateStencil: generateStencil,
  64078. isCube: this.isCube
  64079. });
  64080. engine.setFrameBufferDepthStencilTexture(this);
  64081. };
  64082. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64083. if (size.ratio) {
  64084. this._sizeRatio = size.ratio;
  64085. this._size = {
  64086. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64087. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64088. };
  64089. }
  64090. else {
  64091. this._size = size;
  64092. }
  64093. };
  64094. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64095. get: function () {
  64096. return this._samples;
  64097. },
  64098. set: function (value) {
  64099. if (this._samples === value) {
  64100. return;
  64101. }
  64102. var scene = this.getScene();
  64103. if (!scene) {
  64104. return;
  64105. }
  64106. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64107. },
  64108. enumerable: true,
  64109. configurable: true
  64110. });
  64111. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64112. this._currentRefreshId = -1;
  64113. };
  64114. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64115. get: function () {
  64116. return this._refreshRate;
  64117. },
  64118. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64119. set: function (value) {
  64120. this._refreshRate = value;
  64121. this.resetRefreshCounter();
  64122. },
  64123. enumerable: true,
  64124. configurable: true
  64125. });
  64126. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64127. if (!this._postProcessManager) {
  64128. var scene = this.getScene();
  64129. if (!scene) {
  64130. return;
  64131. }
  64132. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64133. this._postProcesses = new Array();
  64134. }
  64135. this._postProcesses.push(postProcess);
  64136. this._postProcesses[0].autoClear = false;
  64137. };
  64138. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64139. if (!this._postProcesses) {
  64140. return;
  64141. }
  64142. if (dispose) {
  64143. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64144. var postProcess = _a[_i];
  64145. postProcess.dispose();
  64146. }
  64147. }
  64148. this._postProcesses = [];
  64149. };
  64150. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64151. if (!this._postProcesses) {
  64152. return;
  64153. }
  64154. var index = this._postProcesses.indexOf(postProcess);
  64155. if (index === -1) {
  64156. return;
  64157. }
  64158. this._postProcesses.splice(index, 1);
  64159. if (this._postProcesses.length > 0) {
  64160. this._postProcesses[0].autoClear = false;
  64161. }
  64162. };
  64163. RenderTargetTexture.prototype._shouldRender = function () {
  64164. if (this._currentRefreshId === -1) { // At least render once
  64165. this._currentRefreshId = 1;
  64166. return true;
  64167. }
  64168. if (this.refreshRate === this._currentRefreshId) {
  64169. this._currentRefreshId = 1;
  64170. return true;
  64171. }
  64172. this._currentRefreshId++;
  64173. return false;
  64174. };
  64175. RenderTargetTexture.prototype.getRenderSize = function () {
  64176. if (this._size.width) {
  64177. return this._size.width;
  64178. }
  64179. return this._size;
  64180. };
  64181. RenderTargetTexture.prototype.getRenderWidth = function () {
  64182. if (this._size.width) {
  64183. return this._size.width;
  64184. }
  64185. return this._size;
  64186. };
  64187. RenderTargetTexture.prototype.getRenderHeight = function () {
  64188. if (this._size.width) {
  64189. return this._size.height;
  64190. }
  64191. return this._size;
  64192. };
  64193. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64194. get: function () {
  64195. return true;
  64196. },
  64197. enumerable: true,
  64198. configurable: true
  64199. });
  64200. RenderTargetTexture.prototype.scale = function (ratio) {
  64201. var newSize = this.getRenderSize() * ratio;
  64202. this.resize(newSize);
  64203. };
  64204. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64205. if (this.isCube) {
  64206. return this._textureMatrix;
  64207. }
  64208. return _super.prototype.getReflectionTextureMatrix.call(this);
  64209. };
  64210. RenderTargetTexture.prototype.resize = function (size) {
  64211. this.releaseInternalTexture();
  64212. var scene = this.getScene();
  64213. if (!scene) {
  64214. return;
  64215. }
  64216. this._processSizeParameter(size);
  64217. if (this.isCube) {
  64218. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64219. }
  64220. else {
  64221. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64222. }
  64223. };
  64224. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64225. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64226. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64227. var scene = this.getScene();
  64228. if (!scene) {
  64229. return;
  64230. }
  64231. var engine = scene.getEngine();
  64232. if (this.useCameraPostProcesses !== undefined) {
  64233. useCameraPostProcess = this.useCameraPostProcesses;
  64234. }
  64235. if (this._waitingRenderList) {
  64236. this.renderList = [];
  64237. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64238. var id = this._waitingRenderList[index];
  64239. var mesh_1 = scene.getMeshByID(id);
  64240. if (mesh_1) {
  64241. this.renderList.push(mesh_1);
  64242. }
  64243. }
  64244. delete this._waitingRenderList;
  64245. }
  64246. // Is predicate defined?
  64247. if (this.renderListPredicate) {
  64248. if (this.renderList) {
  64249. this.renderList.splice(0); // Clear previous renderList
  64250. }
  64251. else {
  64252. this.renderList = [];
  64253. }
  64254. var scene = this.getScene();
  64255. if (!scene) {
  64256. return;
  64257. }
  64258. var sceneMeshes = scene.meshes;
  64259. for (var index = 0; index < sceneMeshes.length; index++) {
  64260. var mesh = sceneMeshes[index];
  64261. if (this.renderListPredicate(mesh)) {
  64262. this.renderList.push(mesh);
  64263. }
  64264. }
  64265. }
  64266. this.onBeforeBindObservable.notifyObservers(this);
  64267. // Set custom projection.
  64268. // Needs to be before binding to prevent changing the aspect ratio.
  64269. var camera;
  64270. if (this.activeCamera) {
  64271. camera = this.activeCamera;
  64272. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64273. if (this.activeCamera !== scene.activeCamera) {
  64274. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64275. }
  64276. }
  64277. else {
  64278. camera = scene.activeCamera;
  64279. if (camera) {
  64280. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64281. }
  64282. }
  64283. // Prepare renderingManager
  64284. this._renderingManager.reset();
  64285. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64286. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64287. var sceneRenderId = scene.getRenderId();
  64288. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64289. var mesh = currentRenderList[meshIndex];
  64290. if (mesh) {
  64291. if (!mesh.isReady(this.refreshRate === 0)) {
  64292. this.resetRefreshCounter();
  64293. continue;
  64294. }
  64295. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64296. var isMasked = void 0;
  64297. if (!this.renderList && camera) {
  64298. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64299. }
  64300. else {
  64301. isMasked = false;
  64302. }
  64303. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64304. mesh._activate(sceneRenderId);
  64305. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64306. var subMesh = mesh.subMeshes[subIndex];
  64307. scene._activeIndices.addCount(subMesh.indexCount, false);
  64308. this._renderingManager.dispatch(subMesh, mesh);
  64309. }
  64310. }
  64311. }
  64312. }
  64313. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64314. var particleSystem = scene.particleSystems[particleIndex];
  64315. var emitter = particleSystem.emitter;
  64316. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64317. continue;
  64318. }
  64319. if (currentRenderList.indexOf(emitter) >= 0) {
  64320. this._renderingManager.dispatchParticles(particleSystem);
  64321. }
  64322. }
  64323. if (this.isCube) {
  64324. for (var face = 0; face < 6; face++) {
  64325. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64326. scene.incrementRenderId();
  64327. scene.resetCachedMaterial();
  64328. }
  64329. }
  64330. else {
  64331. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64332. }
  64333. this.onAfterUnbindObservable.notifyObservers(this);
  64334. if (scene.activeCamera) {
  64335. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64336. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64337. }
  64338. engine.setViewport(scene.activeCamera.viewport);
  64339. }
  64340. scene.resetCachedMaterial();
  64341. };
  64342. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64343. var minimum = 128;
  64344. var x = renderDimension * scale;
  64345. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64346. // Ensure we don't exceed the render dimension (while staying POT)
  64347. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64348. };
  64349. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64350. var _this = this;
  64351. if (!this._texture) {
  64352. return;
  64353. }
  64354. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64355. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64356. });
  64357. };
  64358. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64359. var scene = this.getScene();
  64360. if (!scene) {
  64361. return;
  64362. }
  64363. var engine = scene.getEngine();
  64364. if (!this._texture) {
  64365. return;
  64366. }
  64367. // Bind
  64368. if (this._postProcessManager) {
  64369. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64370. }
  64371. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64372. if (this._texture) {
  64373. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64374. }
  64375. }
  64376. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64377. // Clear
  64378. if (this.onClearObservable.hasObservers()) {
  64379. this.onClearObservable.notifyObservers(engine);
  64380. }
  64381. else {
  64382. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64383. }
  64384. if (!this._doNotChangeAspectRatio) {
  64385. scene.updateTransformMatrix(true);
  64386. }
  64387. // Render
  64388. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64389. if (this._postProcessManager) {
  64390. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64391. }
  64392. else if (useCameraPostProcess) {
  64393. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64394. }
  64395. if (!this._doNotChangeAspectRatio) {
  64396. scene.updateTransformMatrix(true);
  64397. }
  64398. // Dump ?
  64399. if (dumpForDebug) {
  64400. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64401. }
  64402. // Unbind
  64403. if (!this.isCube || faceIndex === 5) {
  64404. if (this.isCube) {
  64405. if (faceIndex === 5) {
  64406. engine.generateMipMapsForCubemap(this._texture);
  64407. }
  64408. }
  64409. this.unbindFrameBuffer(engine, faceIndex);
  64410. }
  64411. else {
  64412. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64413. }
  64414. };
  64415. /**
  64416. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64417. * This allowed control for front to back rendering or reversly depending of the special needs.
  64418. *
  64419. * @param renderingGroupId The rendering group id corresponding to its index
  64420. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64421. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64422. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64423. */
  64424. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64425. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64426. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64427. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64428. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64429. };
  64430. /**
  64431. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64432. *
  64433. * @param renderingGroupId The rendering group id corresponding to its index
  64434. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64435. */
  64436. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64437. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64438. };
  64439. RenderTargetTexture.prototype.clone = function () {
  64440. var textureSize = this.getSize();
  64441. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  64442. // Base texture
  64443. newTexture.hasAlpha = this.hasAlpha;
  64444. newTexture.level = this.level;
  64445. // RenderTarget Texture
  64446. newTexture.coordinatesMode = this.coordinatesMode;
  64447. if (this.renderList) {
  64448. newTexture.renderList = this.renderList.slice(0);
  64449. }
  64450. return newTexture;
  64451. };
  64452. RenderTargetTexture.prototype.serialize = function () {
  64453. if (!this.name) {
  64454. return null;
  64455. }
  64456. var serializationObject = _super.prototype.serialize.call(this);
  64457. serializationObject.renderTargetSize = this.getRenderSize();
  64458. serializationObject.renderList = [];
  64459. if (this.renderList) {
  64460. for (var index = 0; index < this.renderList.length; index++) {
  64461. serializationObject.renderList.push(this.renderList[index].id);
  64462. }
  64463. }
  64464. return serializationObject;
  64465. };
  64466. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64467. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64468. var objBuffer = this.getInternalTexture();
  64469. var scene = this.getScene();
  64470. if (objBuffer && scene) {
  64471. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64472. }
  64473. };
  64474. RenderTargetTexture.prototype.dispose = function () {
  64475. if (this._postProcessManager) {
  64476. this._postProcessManager.dispose();
  64477. this._postProcessManager = null;
  64478. }
  64479. this.clearPostProcesses(true);
  64480. if (this._resizeObserver) {
  64481. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64482. this._resizeObserver = null;
  64483. }
  64484. this.renderList = null;
  64485. // Remove from custom render targets
  64486. var scene = this.getScene();
  64487. if (!scene) {
  64488. return;
  64489. }
  64490. var index = scene.customRenderTargets.indexOf(this);
  64491. if (index >= 0) {
  64492. scene.customRenderTargets.splice(index, 1);
  64493. }
  64494. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64495. var camera = _a[_i];
  64496. index = camera.customRenderTargets.indexOf(this);
  64497. if (index >= 0) {
  64498. camera.customRenderTargets.splice(index, 1);
  64499. }
  64500. }
  64501. _super.prototype.dispose.call(this);
  64502. };
  64503. RenderTargetTexture.prototype._rebuild = function () {
  64504. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64505. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64506. }
  64507. if (this._postProcessManager) {
  64508. this._postProcessManager._rebuild();
  64509. }
  64510. };
  64511. /**
  64512. * Clear the info related to rendering groups preventing retention point in material dispose.
  64513. */
  64514. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64515. if (this._renderingManager) {
  64516. this._renderingManager.freeRenderingGroups();
  64517. }
  64518. };
  64519. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64520. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64521. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64522. return RenderTargetTexture;
  64523. }(BABYLON.Texture));
  64524. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64525. })(BABYLON || (BABYLON = {}));
  64526. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64527. var BABYLON;
  64528. (function (BABYLON) {
  64529. ;
  64530. var MultiRenderTarget = /** @class */ (function (_super) {
  64531. __extends(MultiRenderTarget, _super);
  64532. function MultiRenderTarget(name, size, count, scene, options) {
  64533. var _this = this;
  64534. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64535. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64536. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64537. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64538. _this._engine = scene.getEngine();
  64539. if (!_this.isSupported) {
  64540. _this.dispose();
  64541. return;
  64542. }
  64543. var types = [];
  64544. var samplingModes = [];
  64545. for (var i = 0; i < count; i++) {
  64546. if (options && options.types && options.types[i] !== undefined) {
  64547. types.push(options.types[i]);
  64548. }
  64549. else {
  64550. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64551. }
  64552. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64553. samplingModes.push(options.samplingModes[i]);
  64554. }
  64555. else {
  64556. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64557. }
  64558. }
  64559. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64560. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64561. _this._size = size;
  64562. _this._multiRenderTargetOptions = {
  64563. samplingModes: samplingModes,
  64564. generateMipMaps: generateMipMaps,
  64565. generateDepthBuffer: generateDepthBuffer,
  64566. generateStencilBuffer: generateStencilBuffer,
  64567. generateDepthTexture: generateDepthTexture,
  64568. types: types,
  64569. textureCount: count
  64570. };
  64571. _this._createInternalTextures();
  64572. _this._createTextures();
  64573. return _this;
  64574. }
  64575. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64576. get: function () {
  64577. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64578. },
  64579. enumerable: true,
  64580. configurable: true
  64581. });
  64582. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64583. get: function () {
  64584. return this._textures;
  64585. },
  64586. enumerable: true,
  64587. configurable: true
  64588. });
  64589. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64590. get: function () {
  64591. return this._textures[this._textures.length - 1];
  64592. },
  64593. enumerable: true,
  64594. configurable: true
  64595. });
  64596. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64597. set: function (wrap) {
  64598. if (this._textures) {
  64599. for (var i = 0; i < this._textures.length; i++) {
  64600. this._textures[i].wrapU = wrap;
  64601. }
  64602. }
  64603. },
  64604. enumerable: true,
  64605. configurable: true
  64606. });
  64607. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64608. set: function (wrap) {
  64609. if (this._textures) {
  64610. for (var i = 0; i < this._textures.length; i++) {
  64611. this._textures[i].wrapV = wrap;
  64612. }
  64613. }
  64614. },
  64615. enumerable: true,
  64616. configurable: true
  64617. });
  64618. MultiRenderTarget.prototype._rebuild = function () {
  64619. this.releaseInternalTextures();
  64620. this._createInternalTextures();
  64621. for (var i = 0; i < this._internalTextures.length; i++) {
  64622. var texture = this._textures[i];
  64623. texture._texture = this._internalTextures[i];
  64624. }
  64625. // Keeps references to frame buffer and stencil/depth buffer
  64626. this._texture = this._internalTextures[0];
  64627. };
  64628. MultiRenderTarget.prototype._createInternalTextures = function () {
  64629. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64630. };
  64631. MultiRenderTarget.prototype._createTextures = function () {
  64632. this._textures = [];
  64633. for (var i = 0; i < this._internalTextures.length; i++) {
  64634. var texture = new BABYLON.Texture(null, this.getScene());
  64635. texture._texture = this._internalTextures[i];
  64636. this._textures.push(texture);
  64637. }
  64638. // Keeps references to frame buffer and stencil/depth buffer
  64639. this._texture = this._internalTextures[0];
  64640. };
  64641. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64642. get: function () {
  64643. return this._samples;
  64644. },
  64645. set: function (value) {
  64646. if (this._samples === value) {
  64647. return;
  64648. }
  64649. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64650. },
  64651. enumerable: true,
  64652. configurable: true
  64653. });
  64654. MultiRenderTarget.prototype.resize = function (size) {
  64655. this.releaseInternalTextures();
  64656. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64657. this._createInternalTextures();
  64658. };
  64659. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64660. var _this = this;
  64661. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64662. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64663. });
  64664. };
  64665. MultiRenderTarget.prototype.dispose = function () {
  64666. this.releaseInternalTextures();
  64667. _super.prototype.dispose.call(this);
  64668. };
  64669. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64670. if (!this._internalTextures) {
  64671. return;
  64672. }
  64673. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64674. if (this._internalTextures[i] !== undefined) {
  64675. this._internalTextures[i].dispose();
  64676. this._internalTextures.splice(i, 1);
  64677. }
  64678. }
  64679. };
  64680. return MultiRenderTarget;
  64681. }(BABYLON.RenderTargetTexture));
  64682. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64683. })(BABYLON || (BABYLON = {}));
  64684. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64685. var BABYLON;
  64686. (function (BABYLON) {
  64687. var MirrorTexture = /** @class */ (function (_super) {
  64688. __extends(MirrorTexture, _super);
  64689. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64690. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64692. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64693. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64694. _this.scene = scene;
  64695. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64696. _this._transformMatrix = BABYLON.Matrix.Zero();
  64697. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64698. _this._adaptiveBlurKernel = 0;
  64699. _this._blurKernelX = 0;
  64700. _this._blurKernelY = 0;
  64701. _this._blurRatio = 1.0;
  64702. _this.ignoreCameraViewport = true;
  64703. _this._updateGammaSpace();
  64704. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64705. _this._updateGammaSpace;
  64706. });
  64707. _this.onBeforeRenderObservable.add(function () {
  64708. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64709. _this._savedViewMatrix = scene.getViewMatrix();
  64710. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64711. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64712. scene.clipPlane = _this.mirrorPlane;
  64713. scene.getEngine().cullBackFaces = false;
  64714. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64715. });
  64716. _this.onAfterRenderObservable.add(function () {
  64717. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64718. scene.getEngine().cullBackFaces = true;
  64719. scene._mirroredCameraPosition = null;
  64720. delete scene.clipPlane;
  64721. });
  64722. return _this;
  64723. }
  64724. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64725. get: function () {
  64726. return this._blurRatio;
  64727. },
  64728. set: function (value) {
  64729. if (this._blurRatio === value) {
  64730. return;
  64731. }
  64732. this._blurRatio = value;
  64733. this._preparePostProcesses();
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64739. set: function (value) {
  64740. this._adaptiveBlurKernel = value;
  64741. this._autoComputeBlurKernel();
  64742. },
  64743. enumerable: true,
  64744. configurable: true
  64745. });
  64746. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64747. set: function (value) {
  64748. this.blurKernelX = value;
  64749. this.blurKernelY = value;
  64750. },
  64751. enumerable: true,
  64752. configurable: true
  64753. });
  64754. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64755. get: function () {
  64756. return this._blurKernelX;
  64757. },
  64758. set: function (value) {
  64759. if (this._blurKernelX === value) {
  64760. return;
  64761. }
  64762. this._blurKernelX = value;
  64763. this._preparePostProcesses();
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64769. get: function () {
  64770. return this._blurKernelY;
  64771. },
  64772. set: function (value) {
  64773. if (this._blurKernelY === value) {
  64774. return;
  64775. }
  64776. this._blurKernelY = value;
  64777. this._preparePostProcesses();
  64778. },
  64779. enumerable: true,
  64780. configurable: true
  64781. });
  64782. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64783. var engine = this.getScene().getEngine();
  64784. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64785. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64786. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64787. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64788. };
  64789. MirrorTexture.prototype._onRatioRescale = function () {
  64790. if (this._sizeRatio) {
  64791. this.resize(this._initialSizeParameter);
  64792. if (!this._adaptiveBlurKernel) {
  64793. this._preparePostProcesses();
  64794. }
  64795. }
  64796. if (this._adaptiveBlurKernel) {
  64797. this._autoComputeBlurKernel();
  64798. }
  64799. };
  64800. MirrorTexture.prototype._updateGammaSpace = function () {
  64801. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64802. };
  64803. MirrorTexture.prototype._preparePostProcesses = function () {
  64804. this.clearPostProcesses(true);
  64805. if (this._blurKernelX && this._blurKernelY) {
  64806. var engine = this.getScene().getEngine();
  64807. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64808. 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);
  64809. this._blurX.autoClear = false;
  64810. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64811. this._blurX.inputTexture = this._texture;
  64812. }
  64813. else {
  64814. this._blurX.alwaysForcePOT = true;
  64815. }
  64816. 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);
  64817. this._blurY.autoClear = false;
  64818. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64819. this.addPostProcess(this._blurX);
  64820. this.addPostProcess(this._blurY);
  64821. }
  64822. else {
  64823. if (this._blurY) {
  64824. this.removePostProcess(this._blurY);
  64825. this._blurY.dispose();
  64826. this._blurY = null;
  64827. }
  64828. if (this._blurX) {
  64829. this.removePostProcess(this._blurX);
  64830. this._blurX.dispose();
  64831. this._blurX = null;
  64832. }
  64833. }
  64834. };
  64835. MirrorTexture.prototype.clone = function () {
  64836. var scene = this.getScene();
  64837. if (!scene) {
  64838. return this;
  64839. }
  64840. var textureSize = this.getSize();
  64841. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64842. // Base texture
  64843. newTexture.hasAlpha = this.hasAlpha;
  64844. newTexture.level = this.level;
  64845. // Mirror Texture
  64846. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64847. if (this.renderList) {
  64848. newTexture.renderList = this.renderList.slice(0);
  64849. }
  64850. return newTexture;
  64851. };
  64852. MirrorTexture.prototype.serialize = function () {
  64853. if (!this.name) {
  64854. return null;
  64855. }
  64856. var serializationObject = _super.prototype.serialize.call(this);
  64857. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64858. return serializationObject;
  64859. };
  64860. MirrorTexture.prototype.dispose = function () {
  64861. _super.prototype.dispose.call(this);
  64862. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64863. };
  64864. return MirrorTexture;
  64865. }(BABYLON.RenderTargetTexture));
  64866. BABYLON.MirrorTexture = MirrorTexture;
  64867. })(BABYLON || (BABYLON = {}));
  64868. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64869. var BABYLON;
  64870. (function (BABYLON) {
  64871. /**
  64872. * Creates a refraction texture used by refraction channel of the standard material.
  64873. * @param name the texture name
  64874. * @param size size of the underlying texture
  64875. * @param scene root scene
  64876. */
  64877. var RefractionTexture = /** @class */ (function (_super) {
  64878. __extends(RefractionTexture, _super);
  64879. function RefractionTexture(name, size, scene, generateMipMaps) {
  64880. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64881. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64882. _this.depth = 2.0;
  64883. _this.onBeforeRenderObservable.add(function () {
  64884. scene.clipPlane = _this.refractionPlane;
  64885. });
  64886. _this.onAfterRenderObservable.add(function () {
  64887. delete scene.clipPlane;
  64888. });
  64889. return _this;
  64890. }
  64891. RefractionTexture.prototype.clone = function () {
  64892. var scene = this.getScene();
  64893. if (!scene) {
  64894. return this;
  64895. }
  64896. var textureSize = this.getSize();
  64897. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64898. // Base texture
  64899. newTexture.hasAlpha = this.hasAlpha;
  64900. newTexture.level = this.level;
  64901. // Refraction Texture
  64902. newTexture.refractionPlane = this.refractionPlane.clone();
  64903. if (this.renderList) {
  64904. newTexture.renderList = this.renderList.slice(0);
  64905. }
  64906. newTexture.depth = this.depth;
  64907. return newTexture;
  64908. };
  64909. RefractionTexture.prototype.serialize = function () {
  64910. if (!this.name) {
  64911. return null;
  64912. }
  64913. var serializationObject = _super.prototype.serialize.call(this);
  64914. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64915. serializationObject.depth = this.depth;
  64916. return serializationObject;
  64917. };
  64918. return RefractionTexture;
  64919. }(BABYLON.RenderTargetTexture));
  64920. BABYLON.RefractionTexture = RefractionTexture;
  64921. })(BABYLON || (BABYLON = {}));
  64922. //# sourceMappingURL=babylon.refractionTexture.js.map
  64923. var BABYLON;
  64924. (function (BABYLON) {
  64925. /**
  64926. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64927. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64928. */
  64929. var DynamicTexture = /** @class */ (function (_super) {
  64930. __extends(DynamicTexture, _super);
  64931. /**
  64932. * Creates a {BABYLON.DynamicTexture}
  64933. * @param name defines the name of the texture
  64934. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64935. * @param scene defines the scene where you want the texture
  64936. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64937. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64938. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64939. */
  64940. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64941. if (scene === void 0) { scene = null; }
  64942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64943. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64944. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64945. _this.name = name;
  64946. _this._engine = _this.getScene().getEngine();
  64947. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64948. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64949. _this._generateMipMaps = generateMipMaps;
  64950. if (options.getContext) {
  64951. _this._canvas = options;
  64952. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64953. }
  64954. else {
  64955. _this._canvas = document.createElement("canvas");
  64956. if (options.width || options.width === 0) {
  64957. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64958. }
  64959. else {
  64960. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64961. }
  64962. }
  64963. var textureSize = _this.getSize();
  64964. _this._canvas.width = textureSize.width;
  64965. _this._canvas.height = textureSize.height;
  64966. _this._context = _this._canvas.getContext("2d");
  64967. return _this;
  64968. }
  64969. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64970. /**
  64971. * Gets the current state of canRescale
  64972. */
  64973. get: function () {
  64974. return true;
  64975. },
  64976. enumerable: true,
  64977. configurable: true
  64978. });
  64979. DynamicTexture.prototype._recreate = function (textureSize) {
  64980. this._canvas.width = textureSize.width;
  64981. this._canvas.height = textureSize.height;
  64982. this.releaseInternalTexture();
  64983. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64984. };
  64985. /**
  64986. * Scales the texture
  64987. * @param ratio the scale factor to apply to both width and height
  64988. */
  64989. DynamicTexture.prototype.scale = function (ratio) {
  64990. var textureSize = this.getSize();
  64991. textureSize.width *= ratio;
  64992. textureSize.height *= ratio;
  64993. this._recreate(textureSize);
  64994. };
  64995. /**
  64996. * Resizes the texture
  64997. * @param width the new width
  64998. * @param height the new height
  64999. */
  65000. DynamicTexture.prototype.scaleTo = function (width, height) {
  65001. var textureSize = this.getSize();
  65002. textureSize.width = width;
  65003. textureSize.height = height;
  65004. this._recreate(textureSize);
  65005. };
  65006. /**
  65007. * Gets the context of the canvas used by the texture
  65008. * @returns the canvas context of the dynamic texture
  65009. */
  65010. DynamicTexture.prototype.getContext = function () {
  65011. return this._context;
  65012. };
  65013. /**
  65014. * Clears the texture
  65015. */
  65016. DynamicTexture.prototype.clear = function () {
  65017. var size = this.getSize();
  65018. this._context.fillRect(0, 0, size.width, size.height);
  65019. };
  65020. /**
  65021. * Updates the texture
  65022. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65023. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65024. */
  65025. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65026. if (premulAlpha === void 0) { premulAlpha = false; }
  65027. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65028. };
  65029. /**
  65030. * Draws text onto the texture
  65031. * @param text defines the text to be drawn
  65032. * @param x defines the placement of the text from the left
  65033. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65034. * @param font defines the font to be used with font-style, font-size, font-name
  65035. * @param color defines the color used for the text
  65036. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65037. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65038. * @param update defines whether texture is immediately update (default is true)
  65039. */
  65040. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65041. if (update === void 0) { update = true; }
  65042. var size = this.getSize();
  65043. if (clearColor) {
  65044. this._context.fillStyle = clearColor;
  65045. this._context.fillRect(0, 0, size.width, size.height);
  65046. }
  65047. this._context.font = font;
  65048. if (x === null || x === undefined) {
  65049. var textSize = this._context.measureText(text);
  65050. x = (size.width - textSize.width) / 2;
  65051. }
  65052. if (y === null || y === undefined) {
  65053. var fontSize = parseInt((font.replace(/\D/g, '')));
  65054. y = (size.height / 2) + (fontSize / 3.65);
  65055. }
  65056. this._context.fillStyle = color;
  65057. this._context.fillText(text, x, y);
  65058. if (update) {
  65059. this.update(invertY);
  65060. }
  65061. };
  65062. /**
  65063. * Clones the texture
  65064. * @returns the clone of the texture.
  65065. */
  65066. DynamicTexture.prototype.clone = function () {
  65067. var scene = this.getScene();
  65068. if (!scene) {
  65069. return this;
  65070. }
  65071. var textureSize = this.getSize();
  65072. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65073. // Base texture
  65074. newTexture.hasAlpha = this.hasAlpha;
  65075. newTexture.level = this.level;
  65076. // Dynamic Texture
  65077. newTexture.wrapU = this.wrapU;
  65078. newTexture.wrapV = this.wrapV;
  65079. return newTexture;
  65080. };
  65081. /** @hidden */
  65082. DynamicTexture.prototype._rebuild = function () {
  65083. this.update();
  65084. };
  65085. return DynamicTexture;
  65086. }(BABYLON.Texture));
  65087. BABYLON.DynamicTexture = DynamicTexture;
  65088. })(BABYLON || (BABYLON = {}));
  65089. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65090. var BABYLON;
  65091. (function (BABYLON) {
  65092. var VideoTexture = /** @class */ (function (_super) {
  65093. __extends(VideoTexture, _super);
  65094. /**
  65095. * Creates a video texture.
  65096. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65097. * @param {string | null} name optional name, will detect from video source, if not defined
  65098. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65099. * @param {BABYLON.Scene} scene is obviously the current scene.
  65100. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65101. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65102. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65103. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65104. */
  65105. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65106. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65107. if (invertY === void 0) { invertY = false; }
  65108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65109. if (settings === void 0) { settings = {
  65110. autoPlay: true,
  65111. loop: true,
  65112. autoUpdateTexture: true,
  65113. }; }
  65114. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65115. _this._stillImageCaptured = false;
  65116. _this._createInternalTexture = function () {
  65117. if (_this._texture != null) {
  65118. return;
  65119. }
  65120. if (!_this._engine.needPOTTextures ||
  65121. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65122. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65123. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65124. }
  65125. else {
  65126. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65127. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65128. _this._generateMipMaps = false;
  65129. }
  65130. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65131. if (!_this.video.autoplay) {
  65132. var oldHandler_1 = _this.video.onplaying;
  65133. _this.video.onplaying = function () {
  65134. _this.video.onplaying = oldHandler_1;
  65135. _this._texture.isReady = true;
  65136. _this._updateInternalTexture();
  65137. _this.video.pause();
  65138. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65139. _this.onLoadObservable.notifyObservers(_this);
  65140. }
  65141. };
  65142. _this.video.play();
  65143. }
  65144. else {
  65145. _this._texture.isReady = true;
  65146. _this._updateInternalTexture();
  65147. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65148. _this.onLoadObservable.notifyObservers(_this);
  65149. }
  65150. }
  65151. };
  65152. _this.reset = function () {
  65153. if (_this._texture == null) {
  65154. return;
  65155. }
  65156. _this._texture.dispose();
  65157. _this._texture = null;
  65158. };
  65159. _this._updateInternalTexture = function (e) {
  65160. if (_this._texture == null || !_this._texture.isReady) {
  65161. return;
  65162. }
  65163. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65164. return;
  65165. }
  65166. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65167. };
  65168. _this._engine = _this.getScene().getEngine();
  65169. _this._generateMipMaps = generateMipMaps;
  65170. _this._samplingMode = samplingMode;
  65171. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65172. _this.name = name || _this._getName(src);
  65173. _this.video = _this._getVideo(src);
  65174. if (settings.autoPlay !== undefined) {
  65175. _this.video.autoplay = settings.autoPlay;
  65176. }
  65177. if (settings.loop !== undefined) {
  65178. _this.video.loop = settings.loop;
  65179. }
  65180. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65181. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65182. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65183. _this.video.addEventListener("emptied", _this.reset);
  65184. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65185. _this._createInternalTexture();
  65186. }
  65187. return _this;
  65188. }
  65189. VideoTexture.prototype._getName = function (src) {
  65190. if (src instanceof HTMLVideoElement) {
  65191. return src.currentSrc;
  65192. }
  65193. if (typeof src === "object") {
  65194. return src.toString();
  65195. }
  65196. return src;
  65197. };
  65198. ;
  65199. VideoTexture.prototype._getVideo = function (src) {
  65200. if (src instanceof HTMLVideoElement) {
  65201. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65202. return src;
  65203. }
  65204. var video = document.createElement("video");
  65205. if (typeof src === "string") {
  65206. BABYLON.Tools.SetCorsBehavior(src, video);
  65207. video.src = src;
  65208. }
  65209. else {
  65210. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65211. src.forEach(function (url) {
  65212. var source = document.createElement("source");
  65213. source.src = url;
  65214. video.appendChild(source);
  65215. });
  65216. }
  65217. return video;
  65218. };
  65219. ;
  65220. /**
  65221. * Internal method to initiate `update`.
  65222. */
  65223. VideoTexture.prototype._rebuild = function () {
  65224. this.update();
  65225. };
  65226. /**
  65227. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65228. */
  65229. VideoTexture.prototype.update = function () {
  65230. if (!this.autoUpdateTexture) {
  65231. // Expecting user to call `updateTexture` manually
  65232. return;
  65233. }
  65234. this.updateTexture(true);
  65235. };
  65236. /**
  65237. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65238. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65239. */
  65240. VideoTexture.prototype.updateTexture = function (isVisible) {
  65241. if (!isVisible) {
  65242. return;
  65243. }
  65244. if (this.video.paused && this._stillImageCaptured) {
  65245. return;
  65246. }
  65247. this._stillImageCaptured = true;
  65248. this._updateInternalTexture();
  65249. };
  65250. /**
  65251. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65252. * @param url New url.
  65253. */
  65254. VideoTexture.prototype.updateURL = function (url) {
  65255. this.video.src = url;
  65256. };
  65257. VideoTexture.prototype.dispose = function () {
  65258. _super.prototype.dispose.call(this);
  65259. this.video.removeEventListener("canplay", this._createInternalTexture);
  65260. this.video.removeEventListener("paused", this._updateInternalTexture);
  65261. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65262. this.video.removeEventListener("emptied", this.reset);
  65263. this.video.pause();
  65264. };
  65265. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65266. var video = document.createElement("video");
  65267. var constraintsDeviceId;
  65268. if (constraints && constraints.deviceId) {
  65269. constraintsDeviceId = {
  65270. exact: constraints.deviceId,
  65271. };
  65272. }
  65273. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65274. if (navigator.mediaDevices) {
  65275. navigator.mediaDevices.getUserMedia({ video: constraints })
  65276. .then(function (stream) {
  65277. if (video.mozSrcObject !== undefined) {
  65278. // hack for Firefox < 19
  65279. video.mozSrcObject = stream;
  65280. }
  65281. else {
  65282. video.srcObject = stream;
  65283. }
  65284. var onPlaying = function () {
  65285. if (onReady) {
  65286. onReady(new VideoTexture("video", video, scene, true, true));
  65287. }
  65288. video.removeEventListener("playing", onPlaying);
  65289. };
  65290. video.addEventListener("playing", onPlaying);
  65291. video.play();
  65292. })
  65293. .catch(function (err) {
  65294. BABYLON.Tools.Error(err.name);
  65295. });
  65296. }
  65297. else {
  65298. navigator.getUserMedia =
  65299. navigator.getUserMedia ||
  65300. navigator.webkitGetUserMedia ||
  65301. navigator.mozGetUserMedia ||
  65302. navigator.msGetUserMedia;
  65303. if (navigator.getUserMedia) {
  65304. navigator.getUserMedia({
  65305. video: {
  65306. deviceId: constraintsDeviceId,
  65307. width: {
  65308. min: (constraints && constraints.minWidth) || 256,
  65309. max: (constraints && constraints.maxWidth) || 640,
  65310. },
  65311. height: {
  65312. min: (constraints && constraints.minHeight) || 256,
  65313. max: (constraints && constraints.maxHeight) || 480,
  65314. },
  65315. },
  65316. }, function (stream) {
  65317. if (video.mozSrcObject !== undefined) {
  65318. // hack for Firefox < 19
  65319. video.mozSrcObject = stream;
  65320. }
  65321. else {
  65322. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65323. }
  65324. video.play();
  65325. if (onReady) {
  65326. onReady(new VideoTexture("video", video, scene, true, true));
  65327. }
  65328. }, function (e) {
  65329. BABYLON.Tools.Error(e.name);
  65330. });
  65331. }
  65332. }
  65333. };
  65334. return VideoTexture;
  65335. }(BABYLON.Texture));
  65336. BABYLON.VideoTexture = VideoTexture;
  65337. })(BABYLON || (BABYLON = {}));
  65338. //# sourceMappingURL=babylon.videoTexture.js.map
  65339. var BABYLON;
  65340. (function (BABYLON) {
  65341. var RawTexture = /** @class */ (function (_super) {
  65342. __extends(RawTexture, _super);
  65343. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65344. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65345. if (invertY === void 0) { invertY = false; }
  65346. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65347. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65348. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65349. _this.format = format;
  65350. _this._engine = scene.getEngine();
  65351. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65352. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65353. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65354. return _this;
  65355. }
  65356. RawTexture.prototype.update = function (data) {
  65357. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65358. };
  65359. // Statics
  65360. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65361. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65362. if (invertY === void 0) { invertY = false; }
  65363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65364. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65365. };
  65366. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65367. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65368. if (invertY === void 0) { invertY = false; }
  65369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65370. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65371. };
  65372. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65373. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65374. if (invertY === void 0) { invertY = false; }
  65375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65376. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65377. };
  65378. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65379. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65380. if (invertY === void 0) { invertY = false; }
  65381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65382. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65383. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65384. };
  65385. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65386. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65387. if (invertY === void 0) { invertY = false; }
  65388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65389. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65390. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65391. };
  65392. return RawTexture;
  65393. }(BABYLON.Texture));
  65394. BABYLON.RawTexture = RawTexture;
  65395. })(BABYLON || (BABYLON = {}));
  65396. //# sourceMappingURL=babylon.rawTexture.js.map
  65397. var BABYLON;
  65398. (function (BABYLON) {
  65399. /**
  65400. * Class used to store 3D textures containing user data
  65401. */
  65402. var RawTexture3D = /** @class */ (function (_super) {
  65403. __extends(RawTexture3D, _super);
  65404. /**
  65405. * Create a new RawTexture3D
  65406. * @param data defines the data of the texture
  65407. * @param width defines the width of the texture
  65408. * @param height defines the height of the texture
  65409. * @param depth defines the depth of the texture
  65410. * @param format defines the texture format to use
  65411. * @param scene defines the hosting scene
  65412. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65413. * @param invertY defines if texture must be stored with Y axis inverted
  65414. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65415. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65416. */
  65417. function RawTexture3D(data, width, height, depth,
  65418. /** Gets or sets the texture format to use */
  65419. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65420. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65421. if (invertY === void 0) { invertY = false; }
  65422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65423. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65424. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65425. _this.format = format;
  65426. _this._engine = scene.getEngine();
  65427. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65428. _this.is3D = true;
  65429. return _this;
  65430. }
  65431. /**
  65432. * Update the texture with new data
  65433. * @param data defines the data to store in the texture
  65434. */
  65435. RawTexture3D.prototype.update = function (data) {
  65436. if (!this._texture) {
  65437. return;
  65438. }
  65439. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65440. };
  65441. return RawTexture3D;
  65442. }(BABYLON.Texture));
  65443. BABYLON.RawTexture3D = RawTexture3D;
  65444. })(BABYLON || (BABYLON = {}));
  65445. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65446. var BABYLON;
  65447. (function (BABYLON) {
  65448. /**
  65449. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65450. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65451. */
  65452. var PostProcess = /** @class */ (function () {
  65453. /**
  65454. * Creates a new instance PostProcess
  65455. * @param name The name of the PostProcess.
  65456. * @param fragmentUrl The url of the fragment shader to be used.
  65457. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65458. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65459. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65460. * @param camera The camera to apply the render pass to.
  65461. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65462. * @param engine The engine which the post process will be applied. (default: current engine)
  65463. * @param reusable If the post process can be reused on the same frame. (default: false)
  65464. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65465. * @param textureType Type of textures used when performing the post process. (default: 0)
  65466. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65467. * @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
  65468. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65469. */
  65470. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65472. if (defines === void 0) { defines = null; }
  65473. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65474. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65475. if (blockCompilation === void 0) { blockCompilation = false; }
  65476. this.name = name;
  65477. /**
  65478. * Width of the texture to apply the post process on
  65479. */
  65480. this.width = -1;
  65481. /**
  65482. * Height of the texture to apply the post process on
  65483. */
  65484. this.height = -1;
  65485. /**
  65486. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65487. */
  65488. this._outputTexture = null;
  65489. /**
  65490. * If the buffer needs to be cleared before applying the post process. (default: true)
  65491. * Should be set to false if shader will overwrite all previous pixels.
  65492. */
  65493. this.autoClear = true;
  65494. /**
  65495. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65496. */
  65497. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65498. /**
  65499. * Animations to be used for the post processing
  65500. */
  65501. this.animations = new Array();
  65502. /**
  65503. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65504. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65505. */
  65506. this.enablePixelPerfectMode = false;
  65507. /**
  65508. * Force the postprocess to be applied without taking in account viewport
  65509. */
  65510. this.forceFullscreenViewport = true;
  65511. /**
  65512. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65513. *
  65514. * | Value | Type | Description |
  65515. * | ----- | ----------------------------------- | ----------- |
  65516. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65517. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65518. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65519. *
  65520. */
  65521. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65522. /**
  65523. * Force textures to be a power of two (default: false)
  65524. */
  65525. this.alwaysForcePOT = false;
  65526. /**
  65527. * Number of sample textures (default: 1)
  65528. */
  65529. this.samples = 1;
  65530. /**
  65531. * Modify the scale of the post process to be the same as the viewport (default: false)
  65532. */
  65533. this.adaptScaleToCurrentViewport = false;
  65534. this._reusable = false;
  65535. /**
  65536. * Smart array of input and output textures for the post process.
  65537. */
  65538. this._textures = new BABYLON.SmartArray(2);
  65539. /**
  65540. * The index in _textures that corresponds to the output texture.
  65541. */
  65542. this._currentRenderTextureInd = 0;
  65543. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65544. this._texelSize = BABYLON.Vector2.Zero();
  65545. // Events
  65546. /**
  65547. * An event triggered when the postprocess is activated.
  65548. */
  65549. this.onActivateObservable = new BABYLON.Observable();
  65550. /**
  65551. * An event triggered when the postprocess changes its size.
  65552. */
  65553. this.onSizeChangedObservable = new BABYLON.Observable();
  65554. /**
  65555. * An event triggered when the postprocess applies its effect.
  65556. */
  65557. this.onApplyObservable = new BABYLON.Observable();
  65558. /**
  65559. * An event triggered before rendering the postprocess
  65560. */
  65561. this.onBeforeRenderObservable = new BABYLON.Observable();
  65562. /**
  65563. * An event triggered after rendering the postprocess
  65564. */
  65565. this.onAfterRenderObservable = new BABYLON.Observable();
  65566. if (camera != null) {
  65567. this._camera = camera;
  65568. this._scene = camera.getScene();
  65569. camera.attachPostProcess(this);
  65570. this._engine = this._scene.getEngine();
  65571. this._scene.postProcesses.push(this);
  65572. }
  65573. else if (engine) {
  65574. this._engine = engine;
  65575. this._engine.postProcesses.push(this);
  65576. }
  65577. this._options = options;
  65578. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65579. this._reusable = reusable || false;
  65580. this._textureType = textureType;
  65581. this._samplers = samplers || [];
  65582. this._samplers.push("textureSampler");
  65583. this._fragmentUrl = fragmentUrl;
  65584. this._vertexUrl = vertexUrl;
  65585. this._parameters = parameters || [];
  65586. this._parameters.push("scale");
  65587. this._indexParameters = indexParameters;
  65588. if (!blockCompilation) {
  65589. this.updateEffect(defines);
  65590. }
  65591. }
  65592. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65593. /**
  65594. * A function that is added to the onActivateObservable
  65595. */
  65596. set: function (callback) {
  65597. if (this._onActivateObserver) {
  65598. this.onActivateObservable.remove(this._onActivateObserver);
  65599. }
  65600. if (callback) {
  65601. this._onActivateObserver = this.onActivateObservable.add(callback);
  65602. }
  65603. },
  65604. enumerable: true,
  65605. configurable: true
  65606. });
  65607. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65608. /**
  65609. * A function that is added to the onSizeChangedObservable
  65610. */
  65611. set: function (callback) {
  65612. if (this._onSizeChangedObserver) {
  65613. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65614. }
  65615. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65616. },
  65617. enumerable: true,
  65618. configurable: true
  65619. });
  65620. Object.defineProperty(PostProcess.prototype, "onApply", {
  65621. /**
  65622. * A function that is added to the onApplyObservable
  65623. */
  65624. set: function (callback) {
  65625. if (this._onApplyObserver) {
  65626. this.onApplyObservable.remove(this._onApplyObserver);
  65627. }
  65628. this._onApplyObserver = this.onApplyObservable.add(callback);
  65629. },
  65630. enumerable: true,
  65631. configurable: true
  65632. });
  65633. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65634. /**
  65635. * A function that is added to the onBeforeRenderObservable
  65636. */
  65637. set: function (callback) {
  65638. if (this._onBeforeRenderObserver) {
  65639. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65640. }
  65641. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65642. },
  65643. enumerable: true,
  65644. configurable: true
  65645. });
  65646. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65647. /**
  65648. * A function that is added to the onAfterRenderObservable
  65649. */
  65650. set: function (callback) {
  65651. if (this._onAfterRenderObserver) {
  65652. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65653. }
  65654. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65660. /**
  65661. * 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
  65662. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65663. */
  65664. get: function () {
  65665. return this._textures.data[this._currentRenderTextureInd];
  65666. },
  65667. set: function (value) {
  65668. this._forcedOutputTexture = value;
  65669. },
  65670. enumerable: true,
  65671. configurable: true
  65672. });
  65673. /**
  65674. * Gets the camera which post process is applied to.
  65675. * @returns The camera the post process is applied to.
  65676. */
  65677. PostProcess.prototype.getCamera = function () {
  65678. return this._camera;
  65679. };
  65680. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65681. /**
  65682. * Gets the texel size of the postprocess.
  65683. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65684. */
  65685. get: function () {
  65686. if (this._shareOutputWithPostProcess) {
  65687. return this._shareOutputWithPostProcess.texelSize;
  65688. }
  65689. if (this._forcedOutputTexture) {
  65690. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65691. }
  65692. return this._texelSize;
  65693. },
  65694. enumerable: true,
  65695. configurable: true
  65696. });
  65697. /**
  65698. * Gets the engine which this post process belongs to.
  65699. * @returns The engine the post process was enabled with.
  65700. */
  65701. PostProcess.prototype.getEngine = function () {
  65702. return this._engine;
  65703. };
  65704. /**
  65705. * The effect that is created when initializing the post process.
  65706. * @returns The created effect corrisponding the the postprocess.
  65707. */
  65708. PostProcess.prototype.getEffect = function () {
  65709. return this._effect;
  65710. };
  65711. /**
  65712. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65713. * @param postProcess The post process to share the output with.
  65714. * @returns This post process.
  65715. */
  65716. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65717. this._disposeTextures();
  65718. this._shareOutputWithPostProcess = postProcess;
  65719. return this;
  65720. };
  65721. /**
  65722. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65723. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65724. */
  65725. PostProcess.prototype.useOwnOutput = function () {
  65726. if (this._textures.length == 0) {
  65727. this._textures = new BABYLON.SmartArray(2);
  65728. }
  65729. this._shareOutputWithPostProcess = null;
  65730. };
  65731. /**
  65732. * Updates the effect with the current post process compile time values and recompiles the shader.
  65733. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65734. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65735. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65736. * @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
  65737. * @param onCompiled Called when the shader has been compiled.
  65738. * @param onError Called if there is an error when compiling a shader.
  65739. */
  65740. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65741. if (defines === void 0) { defines = null; }
  65742. if (uniforms === void 0) { uniforms = null; }
  65743. if (samplers === void 0) { samplers = null; }
  65744. 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);
  65745. };
  65746. /**
  65747. * The post process is reusable if it can be used multiple times within one frame.
  65748. * @returns If the post process is reusable
  65749. */
  65750. PostProcess.prototype.isReusable = function () {
  65751. return this._reusable;
  65752. };
  65753. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65754. PostProcess.prototype.markTextureDirty = function () {
  65755. this.width = -1;
  65756. };
  65757. /**
  65758. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65759. * 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.
  65760. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65761. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65762. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65763. * @returns The target texture that was bound to be written to.
  65764. */
  65765. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65766. var _this = this;
  65767. if (sourceTexture === void 0) { sourceTexture = null; }
  65768. camera = camera || this._camera;
  65769. var scene = camera.getScene();
  65770. var engine = scene.getEngine();
  65771. var maxSize = engine.getCaps().maxTextureSize;
  65772. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65773. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65774. // 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
  65775. var webVRCamera = camera.parent;
  65776. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65777. requiredWidth /= 2;
  65778. }
  65779. var desiredWidth = (this._options.width || requiredWidth);
  65780. var desiredHeight = this._options.height || requiredHeight;
  65781. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65782. if (this.adaptScaleToCurrentViewport) {
  65783. var currentViewport = engine.currentViewport;
  65784. if (currentViewport) {
  65785. desiredWidth *= currentViewport.width;
  65786. desiredHeight *= currentViewport.height;
  65787. }
  65788. }
  65789. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65790. if (!this._options.width) {
  65791. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65792. }
  65793. if (!this._options.height) {
  65794. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65795. }
  65796. }
  65797. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65798. if (this._textures.length > 0) {
  65799. for (var i = 0; i < this._textures.length; i++) {
  65800. this._engine._releaseTexture(this._textures.data[i]);
  65801. }
  65802. this._textures.reset();
  65803. }
  65804. this.width = desiredWidth;
  65805. this.height = desiredHeight;
  65806. var textureSize = { width: this.width, height: this.height };
  65807. var textureOptions = {
  65808. generateMipMaps: false,
  65809. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65810. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65811. samplingMode: this.renderTargetSamplingMode,
  65812. type: this._textureType
  65813. };
  65814. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65815. if (this._reusable) {
  65816. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65817. }
  65818. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65819. this.onSizeChangedObservable.notifyObservers(this);
  65820. }
  65821. this._textures.forEach(function (texture) {
  65822. if (texture.samples !== _this.samples) {
  65823. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65824. }
  65825. });
  65826. }
  65827. var target;
  65828. if (this._shareOutputWithPostProcess) {
  65829. target = this._shareOutputWithPostProcess.inputTexture;
  65830. }
  65831. else if (this._forcedOutputTexture) {
  65832. target = this._forcedOutputTexture;
  65833. this.width = this._forcedOutputTexture.width;
  65834. this.height = this._forcedOutputTexture.height;
  65835. }
  65836. else {
  65837. target = this.inputTexture;
  65838. }
  65839. // Bind the input of this post process to be used as the output of the previous post process.
  65840. if (this.enablePixelPerfectMode) {
  65841. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65842. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65843. }
  65844. else {
  65845. this._scaleRatio.copyFromFloats(1, 1);
  65846. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65847. }
  65848. this.onActivateObservable.notifyObservers(camera);
  65849. // Clear
  65850. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65851. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65852. }
  65853. if (this._reusable) {
  65854. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65855. }
  65856. return target;
  65857. };
  65858. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65859. /**
  65860. * If the post process is supported.
  65861. */
  65862. get: function () {
  65863. return this._effect.isSupported;
  65864. },
  65865. enumerable: true,
  65866. configurable: true
  65867. });
  65868. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65869. /**
  65870. * The aspect ratio of the output texture.
  65871. */
  65872. get: function () {
  65873. if (this._shareOutputWithPostProcess) {
  65874. return this._shareOutputWithPostProcess.aspectRatio;
  65875. }
  65876. if (this._forcedOutputTexture) {
  65877. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65878. }
  65879. return this.width / this.height;
  65880. },
  65881. enumerable: true,
  65882. configurable: true
  65883. });
  65884. /**
  65885. * Get a value indicating if the post-process is ready to be used
  65886. * @returns true if the post-process is ready (shader is compiled)
  65887. */
  65888. PostProcess.prototype.isReady = function () {
  65889. return this._effect && this._effect.isReady();
  65890. };
  65891. /**
  65892. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65893. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65894. */
  65895. PostProcess.prototype.apply = function () {
  65896. // Check
  65897. if (!this._effect || !this._effect.isReady())
  65898. return null;
  65899. // States
  65900. this._engine.enableEffect(this._effect);
  65901. this._engine.setState(false);
  65902. this._engine.setDepthBuffer(false);
  65903. this._engine.setDepthWrite(false);
  65904. // Alpha
  65905. this._engine.setAlphaMode(this.alphaMode);
  65906. if (this.alphaConstants) {
  65907. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65908. }
  65909. // Bind the output texture of the preivous post process as the input to this post process.
  65910. var source;
  65911. if (this._shareOutputWithPostProcess) {
  65912. source = this._shareOutputWithPostProcess.inputTexture;
  65913. }
  65914. else if (this._forcedOutputTexture) {
  65915. source = this._forcedOutputTexture;
  65916. }
  65917. else {
  65918. source = this.inputTexture;
  65919. }
  65920. this._effect._bindTexture("textureSampler", source);
  65921. // Parameters
  65922. this._effect.setVector2("scale", this._scaleRatio);
  65923. this.onApplyObservable.notifyObservers(this._effect);
  65924. return this._effect;
  65925. };
  65926. PostProcess.prototype._disposeTextures = function () {
  65927. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65928. return;
  65929. }
  65930. if (this._textures.length > 0) {
  65931. for (var i = 0; i < this._textures.length; i++) {
  65932. this._engine._releaseTexture(this._textures.data[i]);
  65933. }
  65934. }
  65935. this._textures.dispose();
  65936. };
  65937. /**
  65938. * Disposes the post process.
  65939. * @param camera The camera to dispose the post process on.
  65940. */
  65941. PostProcess.prototype.dispose = function (camera) {
  65942. camera = camera || this._camera;
  65943. this._disposeTextures();
  65944. if (this._scene) {
  65945. var index_1 = this._scene.postProcesses.indexOf(this);
  65946. if (index_1 !== -1) {
  65947. this._scene.postProcesses.splice(index_1, 1);
  65948. }
  65949. }
  65950. else {
  65951. var index_2 = this._engine.postProcesses.indexOf(this);
  65952. if (index_2 !== -1) {
  65953. this._engine.postProcesses.splice(index_2, 1);
  65954. }
  65955. }
  65956. if (!camera) {
  65957. return;
  65958. }
  65959. camera.detachPostProcess(this);
  65960. var index = camera._postProcesses.indexOf(this);
  65961. if (index === 0 && camera._postProcesses.length > 0) {
  65962. var firstPostProcess = this._camera._getFirstPostProcess();
  65963. if (firstPostProcess) {
  65964. firstPostProcess.markTextureDirty();
  65965. }
  65966. }
  65967. this.onActivateObservable.clear();
  65968. this.onAfterRenderObservable.clear();
  65969. this.onApplyObservable.clear();
  65970. this.onBeforeRenderObservable.clear();
  65971. this.onSizeChangedObservable.clear();
  65972. };
  65973. return PostProcess;
  65974. }());
  65975. BABYLON.PostProcess = PostProcess;
  65976. })(BABYLON || (BABYLON = {}));
  65977. //# sourceMappingURL=babylon.postProcess.js.map
  65978. var BABYLON;
  65979. (function (BABYLON) {
  65980. var PassPostProcess = /** @class */ (function (_super) {
  65981. __extends(PassPostProcess, _super);
  65982. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65983. if (camera === void 0) { camera = null; }
  65984. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65985. if (blockCompilation === void 0) { blockCompilation = false; }
  65986. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65987. }
  65988. return PassPostProcess;
  65989. }(BABYLON.PostProcess));
  65990. BABYLON.PassPostProcess = PassPostProcess;
  65991. })(BABYLON || (BABYLON = {}));
  65992. //# sourceMappingURL=babylon.passPostProcess.js.map
  65993. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65994. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65995. s = arguments[i];
  65996. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65997. t[p] = s[p];
  65998. }
  65999. return t;
  66000. };
  66001. var BABYLON;
  66002. (function (BABYLON) {
  66003. /**
  66004. * Default implementation IShadowGenerator.
  66005. * This is the main object responsible of generating shadows in the framework.
  66006. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66007. */
  66008. var ShadowGenerator = /** @class */ (function () {
  66009. /**
  66010. * Creates a ShadowGenerator object.
  66011. * A ShadowGenerator is the required tool to use the shadows.
  66012. * Each light casting shadows needs to use its own ShadowGenerator.
  66013. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66014. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66015. * @param light The light object generating the shadows.
  66016. * @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.
  66017. */
  66018. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66019. this._bias = 0.00005;
  66020. this._normalBias = 0;
  66021. this._blurBoxOffset = 1;
  66022. this._blurScale = 2;
  66023. this._blurKernel = 1;
  66024. this._useKernelBlur = false;
  66025. this._filter = ShadowGenerator.FILTER_NONE;
  66026. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66027. this._contactHardeningLightSizeUVRatio = 0.1;
  66028. this._darkness = 0;
  66029. this._transparencyShadow = false;
  66030. /**
  66031. * Controls the extent to which the shadows fade out at the edge of the frustum
  66032. * Used only by directionals and spots
  66033. */
  66034. this.frustumEdgeFalloff = 0;
  66035. /**
  66036. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66037. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66038. * It might on the other hand introduce peter panning.
  66039. */
  66040. this.forceBackFacesOnly = false;
  66041. this._lightDirection = BABYLON.Vector3.Zero();
  66042. this._viewMatrix = BABYLON.Matrix.Zero();
  66043. this._projectionMatrix = BABYLON.Matrix.Zero();
  66044. this._transformMatrix = BABYLON.Matrix.Zero();
  66045. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66046. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66047. this._currentFaceIndex = 0;
  66048. this._currentFaceIndexCache = 0;
  66049. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66050. this._mapSize = mapSize;
  66051. this._light = light;
  66052. this._scene = light.getScene();
  66053. light._shadowGenerator = this;
  66054. // Texture type fallback from float to int if not supported.
  66055. var caps = this._scene.getEngine().getCaps();
  66056. if (!useFullFloatFirst) {
  66057. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66058. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66059. }
  66060. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66061. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66062. }
  66063. else {
  66064. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66065. }
  66066. }
  66067. else {
  66068. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66069. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66070. }
  66071. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66072. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66073. }
  66074. else {
  66075. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66076. }
  66077. }
  66078. this._initializeGenerator();
  66079. this._applyFilterValues();
  66080. }
  66081. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66082. /**
  66083. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66084. */
  66085. get: function () {
  66086. return this._bias;
  66087. },
  66088. /**
  66089. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66090. */
  66091. set: function (bias) {
  66092. this._bias = bias;
  66093. },
  66094. enumerable: true,
  66095. configurable: true
  66096. });
  66097. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66098. /**
  66099. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66100. */
  66101. get: function () {
  66102. return this._normalBias;
  66103. },
  66104. /**
  66105. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66106. */
  66107. set: function (normalBias) {
  66108. this._normalBias = normalBias;
  66109. },
  66110. enumerable: true,
  66111. configurable: true
  66112. });
  66113. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66114. /**
  66115. * Gets the blur box offset: offset applied during the blur pass.
  66116. * Only usefull if useKernelBlur = false
  66117. */
  66118. get: function () {
  66119. return this._blurBoxOffset;
  66120. },
  66121. /**
  66122. * Sets the blur box offset: offset applied during the blur pass.
  66123. * Only usefull if useKernelBlur = false
  66124. */
  66125. set: function (value) {
  66126. if (this._blurBoxOffset === value) {
  66127. return;
  66128. }
  66129. this._blurBoxOffset = value;
  66130. this._disposeBlurPostProcesses();
  66131. },
  66132. enumerable: true,
  66133. configurable: true
  66134. });
  66135. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66136. /**
  66137. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66138. * 2 means half of the size.
  66139. */
  66140. get: function () {
  66141. return this._blurScale;
  66142. },
  66143. /**
  66144. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66145. * 2 means half of the size.
  66146. */
  66147. set: function (value) {
  66148. if (this._blurScale === value) {
  66149. return;
  66150. }
  66151. this._blurScale = value;
  66152. this._disposeBlurPostProcesses();
  66153. },
  66154. enumerable: true,
  66155. configurable: true
  66156. });
  66157. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66158. /**
  66159. * Gets the blur kernel: kernel size of the blur pass.
  66160. * Only usefull if useKernelBlur = true
  66161. */
  66162. get: function () {
  66163. return this._blurKernel;
  66164. },
  66165. /**
  66166. * Sets the blur kernel: kernel size of the blur pass.
  66167. * Only usefull if useKernelBlur = true
  66168. */
  66169. set: function (value) {
  66170. if (this._blurKernel === value) {
  66171. return;
  66172. }
  66173. this._blurKernel = value;
  66174. this._disposeBlurPostProcesses();
  66175. },
  66176. enumerable: true,
  66177. configurable: true
  66178. });
  66179. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66180. /**
  66181. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66182. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66183. */
  66184. get: function () {
  66185. return this._useKernelBlur;
  66186. },
  66187. /**
  66188. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66189. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66190. */
  66191. set: function (value) {
  66192. if (this._useKernelBlur === value) {
  66193. return;
  66194. }
  66195. this._useKernelBlur = value;
  66196. this._disposeBlurPostProcesses();
  66197. },
  66198. enumerable: true,
  66199. configurable: true
  66200. });
  66201. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66202. /**
  66203. * Gets the depth scale used in ESM mode.
  66204. */
  66205. get: function () {
  66206. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66207. },
  66208. /**
  66209. * Sets the depth scale used in ESM mode.
  66210. * This can override the scale stored on the light.
  66211. */
  66212. set: function (value) {
  66213. this._depthScale = value;
  66214. },
  66215. enumerable: true,
  66216. configurable: true
  66217. });
  66218. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66219. /**
  66220. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66221. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66222. */
  66223. get: function () {
  66224. return this._filter;
  66225. },
  66226. /**
  66227. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66228. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66229. */
  66230. set: function (value) {
  66231. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66232. if (this._light.needCube()) {
  66233. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66234. this.useExponentialShadowMap = true;
  66235. return;
  66236. }
  66237. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66238. this.useCloseExponentialShadowMap = true;
  66239. return;
  66240. }
  66241. // PCF on cubemap would also be expensive
  66242. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66243. this.usePoissonSampling = true;
  66244. return;
  66245. }
  66246. }
  66247. // Weblg1 fallback for PCF.
  66248. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66249. if (this._scene.getEngine().webGLVersion === 1) {
  66250. this.usePoissonSampling = true;
  66251. return;
  66252. }
  66253. }
  66254. if (this._filter === value) {
  66255. return;
  66256. }
  66257. this._filter = value;
  66258. this._disposeBlurPostProcesses();
  66259. this._applyFilterValues();
  66260. this._light._markMeshesAsLightDirty();
  66261. },
  66262. enumerable: true,
  66263. configurable: true
  66264. });
  66265. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66266. /**
  66267. * Gets if the current filter is set to Poisson Sampling.
  66268. */
  66269. get: function () {
  66270. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66271. },
  66272. /**
  66273. * Sets the current filter to Poisson Sampling.
  66274. */
  66275. set: function (value) {
  66276. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66277. return;
  66278. }
  66279. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66280. },
  66281. enumerable: true,
  66282. configurable: true
  66283. });
  66284. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66285. /**
  66286. * Gets if the current filter is set to VSM.
  66287. * DEPRECATED. Should use useExponentialShadowMap instead.
  66288. */
  66289. get: function () {
  66290. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66291. return this.useExponentialShadowMap;
  66292. },
  66293. /**
  66294. * Sets the current filter is to VSM.
  66295. * DEPRECATED. Should use useExponentialShadowMap instead.
  66296. */
  66297. set: function (value) {
  66298. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66299. this.useExponentialShadowMap = value;
  66300. },
  66301. enumerable: true,
  66302. configurable: true
  66303. });
  66304. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66305. /**
  66306. * Gets if the current filter is set to blurred VSM.
  66307. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66308. */
  66309. get: function () {
  66310. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66311. return this.useBlurExponentialShadowMap;
  66312. },
  66313. /**
  66314. * Sets the current filter is to blurred VSM.
  66315. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66316. */
  66317. set: function (value) {
  66318. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66319. this.useBlurExponentialShadowMap = value;
  66320. },
  66321. enumerable: true,
  66322. configurable: true
  66323. });
  66324. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66325. /**
  66326. * Gets if the current filter is set to ESM.
  66327. */
  66328. get: function () {
  66329. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66330. },
  66331. /**
  66332. * Sets the current filter is to ESM.
  66333. */
  66334. set: function (value) {
  66335. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66336. return;
  66337. }
  66338. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66339. },
  66340. enumerable: true,
  66341. configurable: true
  66342. });
  66343. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66344. /**
  66345. * Gets if the current filter is set to filtered ESM.
  66346. */
  66347. get: function () {
  66348. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66349. },
  66350. /**
  66351. * Gets if the current filter is set to filtered ESM.
  66352. */
  66353. set: function (value) {
  66354. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66355. return;
  66356. }
  66357. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66358. },
  66359. enumerable: true,
  66360. configurable: true
  66361. });
  66362. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66363. /**
  66364. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66365. * exponential to prevent steep falloff artifacts).
  66366. */
  66367. get: function () {
  66368. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66369. },
  66370. /**
  66371. * Sets the current filter to "close ESM" (using the inverse of the
  66372. * exponential to prevent steep falloff artifacts).
  66373. */
  66374. set: function (value) {
  66375. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66376. return;
  66377. }
  66378. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66379. },
  66380. enumerable: true,
  66381. configurable: true
  66382. });
  66383. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66384. /**
  66385. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66386. * exponential to prevent steep falloff artifacts).
  66387. */
  66388. get: function () {
  66389. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66390. },
  66391. /**
  66392. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66393. * exponential to prevent steep falloff artifacts).
  66394. */
  66395. set: function (value) {
  66396. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66397. return;
  66398. }
  66399. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66400. },
  66401. enumerable: true,
  66402. configurable: true
  66403. });
  66404. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66405. /**
  66406. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66407. */
  66408. get: function () {
  66409. return this.filter === ShadowGenerator.FILTER_PCF;
  66410. },
  66411. /**
  66412. * Sets the current filter to "PCF" (percentage closer filtering).
  66413. */
  66414. set: function (value) {
  66415. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66416. return;
  66417. }
  66418. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66419. },
  66420. enumerable: true,
  66421. configurable: true
  66422. });
  66423. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66424. /**
  66425. * Gets the PCF or PCSS Quality.
  66426. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66427. */
  66428. get: function () {
  66429. return this._filteringQuality;
  66430. },
  66431. /**
  66432. * Sets the PCF or PCSS Quality.
  66433. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66434. */
  66435. set: function (filteringQuality) {
  66436. this._filteringQuality = filteringQuality;
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66442. /**
  66443. * Gets if the current filter is set to "PCSS" (contact hardening).
  66444. */
  66445. get: function () {
  66446. return this.filter === ShadowGenerator.FILTER_PCSS;
  66447. },
  66448. /**
  66449. * Sets the current filter to "PCSS" (contact hardening).
  66450. */
  66451. set: function (value) {
  66452. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66453. return;
  66454. }
  66455. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66456. },
  66457. enumerable: true,
  66458. configurable: true
  66459. });
  66460. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66461. /**
  66462. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66463. * Using a ratio helps keeping shape stability independently of the map size.
  66464. *
  66465. * It does not account for the light projection as it was having too much
  66466. * instability during the light setup or during light position changes.
  66467. *
  66468. * Only valid if useContactHardeningShadow is true.
  66469. */
  66470. get: function () {
  66471. return this._contactHardeningLightSizeUVRatio;
  66472. },
  66473. /**
  66474. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66475. * Using a ratio helps keeping shape stability independently of the map size.
  66476. *
  66477. * It does not account for the light projection as it was having too much
  66478. * instability during the light setup or during light position changes.
  66479. *
  66480. * Only valid if useContactHardeningShadow is true.
  66481. */
  66482. set: function (contactHardeningLightSizeUVRatio) {
  66483. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66484. },
  66485. enumerable: true,
  66486. configurable: true
  66487. });
  66488. /**
  66489. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66490. * 0 means strongest and 1 would means no shadow.
  66491. * @returns the darkness.
  66492. */
  66493. ShadowGenerator.prototype.getDarkness = function () {
  66494. return this._darkness;
  66495. };
  66496. /**
  66497. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66498. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66499. * @returns the shadow generator allowing fluent coding.
  66500. */
  66501. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66502. if (darkness >= 1.0)
  66503. this._darkness = 1.0;
  66504. else if (darkness <= 0.0)
  66505. this._darkness = 0.0;
  66506. else
  66507. this._darkness = darkness;
  66508. return this;
  66509. };
  66510. /**
  66511. * Sets the ability to have transparent shadow (boolean).
  66512. * @param transparent True if transparent else False
  66513. * @returns the shadow generator allowing fluent coding
  66514. */
  66515. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66516. this._transparencyShadow = transparent;
  66517. return this;
  66518. };
  66519. /**
  66520. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66521. * @returns The render target texture if present otherwise, null
  66522. */
  66523. ShadowGenerator.prototype.getShadowMap = function () {
  66524. return this._shadowMap;
  66525. };
  66526. /**
  66527. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66528. * @returns The render target texture if the shadow map is present otherwise, null
  66529. */
  66530. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66531. if (this._shadowMap2) {
  66532. return this._shadowMap2;
  66533. }
  66534. return this._shadowMap;
  66535. };
  66536. /**
  66537. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66538. * @param mesh Mesh to add
  66539. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66540. * @returns the Shadow Generator itself
  66541. */
  66542. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66543. if (includeDescendants === void 0) { includeDescendants = true; }
  66544. if (!this._shadowMap) {
  66545. return this;
  66546. }
  66547. if (!this._shadowMap.renderList) {
  66548. this._shadowMap.renderList = [];
  66549. }
  66550. this._shadowMap.renderList.push(mesh);
  66551. if (includeDescendants) {
  66552. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66553. }
  66554. return this;
  66555. var _a;
  66556. };
  66557. /**
  66558. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66559. * @param mesh Mesh to remove
  66560. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66561. * @returns the Shadow Generator itself
  66562. */
  66563. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66564. if (includeDescendants === void 0) { includeDescendants = true; }
  66565. if (!this._shadowMap || !this._shadowMap.renderList) {
  66566. return this;
  66567. }
  66568. var index = this._shadowMap.renderList.indexOf(mesh);
  66569. if (index !== -1) {
  66570. this._shadowMap.renderList.splice(index, 1);
  66571. }
  66572. if (includeDescendants) {
  66573. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66574. var child = _a[_i];
  66575. this.removeShadowCaster(child);
  66576. }
  66577. }
  66578. return this;
  66579. };
  66580. /**
  66581. * Returns the associated light object.
  66582. * @returns the light generating the shadow
  66583. */
  66584. ShadowGenerator.prototype.getLight = function () {
  66585. return this._light;
  66586. };
  66587. ShadowGenerator.prototype._initializeGenerator = function () {
  66588. this._light._markMeshesAsLightDirty();
  66589. this._initializeShadowMap();
  66590. };
  66591. ShadowGenerator.prototype._initializeShadowMap = function () {
  66592. var _this = this;
  66593. // Render target
  66594. var engine = this._scene.getEngine();
  66595. if (engine.webGLVersion > 1) {
  66596. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66597. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66598. }
  66599. else {
  66600. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66601. }
  66602. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66603. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66604. this._shadowMap.anisotropicFilteringLevel = 1;
  66605. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66606. this._shadowMap.renderParticles = false;
  66607. this._shadowMap.ignoreCameraViewport = true;
  66608. // Record Face Index before render.
  66609. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66610. _this._currentFaceIndex = faceIndex;
  66611. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66612. engine.setColorWrite(false);
  66613. }
  66614. });
  66615. // Custom render function.
  66616. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66617. // Blur if required afer render.
  66618. this._shadowMap.onAfterUnbindObservable.add(function () {
  66619. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66620. engine.setColorWrite(true);
  66621. }
  66622. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66623. return;
  66624. }
  66625. var shadowMap = _this.getShadowMapForRendering();
  66626. if (shadowMap) {
  66627. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66628. }
  66629. });
  66630. // Clear according to the chosen filter.
  66631. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66632. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66633. this._shadowMap.onClearObservable.add(function (engine) {
  66634. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66635. engine.clear(clearOne, false, true, false);
  66636. }
  66637. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66638. engine.clear(clearZero, true, true, false);
  66639. }
  66640. else {
  66641. engine.clear(clearOne, true, true, false);
  66642. }
  66643. });
  66644. };
  66645. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66646. var _this = this;
  66647. var engine = this._scene.getEngine();
  66648. var targetSize = this._mapSize / this.blurScale;
  66649. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66650. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66651. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66652. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66653. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66654. }
  66655. if (this.useKernelBlur) {
  66656. 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);
  66657. this._kernelBlurXPostprocess.width = targetSize;
  66658. this._kernelBlurXPostprocess.height = targetSize;
  66659. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66660. effect.setTexture("textureSampler", _this._shadowMap);
  66661. });
  66662. 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);
  66663. this._kernelBlurXPostprocess.autoClear = false;
  66664. this._kernelBlurYPostprocess.autoClear = false;
  66665. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66666. this._kernelBlurXPostprocess.packedFloat = true;
  66667. this._kernelBlurYPostprocess.packedFloat = true;
  66668. }
  66669. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66670. }
  66671. else {
  66672. 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);
  66673. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66674. effect.setFloat2("screenSize", targetSize, targetSize);
  66675. effect.setTexture("textureSampler", _this._shadowMap);
  66676. });
  66677. this._boxBlurPostprocess.autoClear = false;
  66678. this._blurPostProcesses = [this._boxBlurPostprocess];
  66679. }
  66680. };
  66681. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66682. var index;
  66683. var engine = this._scene.getEngine();
  66684. if (depthOnlySubMeshes.length) {
  66685. engine.setColorWrite(false);
  66686. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66687. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66688. }
  66689. engine.setColorWrite(true);
  66690. }
  66691. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66692. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66693. }
  66694. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66695. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66696. }
  66697. if (this._transparencyShadow) {
  66698. for (index = 0; index < transparentSubMeshes.length; index++) {
  66699. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66700. }
  66701. }
  66702. };
  66703. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66704. var _this = this;
  66705. var mesh = subMesh.getRenderingMesh();
  66706. var scene = this._scene;
  66707. var engine = scene.getEngine();
  66708. var material = subMesh.getMaterial();
  66709. if (!material) {
  66710. return;
  66711. }
  66712. // Culling
  66713. engine.setState(material.backFaceCulling);
  66714. // Managing instances
  66715. var batch = mesh._getInstancesRenderList(subMesh._id);
  66716. if (batch.mustReturn) {
  66717. return;
  66718. }
  66719. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66720. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66721. engine.enableEffect(this._effect);
  66722. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66723. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66724. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66725. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66726. this._effect.setVector3("lightData", this._cachedDirection);
  66727. }
  66728. else {
  66729. this._effect.setVector3("lightData", this._cachedPosition);
  66730. }
  66731. if (scene.activeCamera) {
  66732. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66733. }
  66734. // Alpha test
  66735. if (material && material.needAlphaTesting()) {
  66736. var alphaTexture = material.getAlphaTestTexture();
  66737. if (alphaTexture) {
  66738. this._effect.setTexture("diffuseSampler", alphaTexture);
  66739. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66740. }
  66741. }
  66742. // Bones
  66743. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66744. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66745. }
  66746. // Morph targets
  66747. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66748. if (this.forceBackFacesOnly) {
  66749. engine.setState(true, 0, false, true);
  66750. }
  66751. // Draw
  66752. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66753. if (this.forceBackFacesOnly) {
  66754. engine.setState(true, 0, false, false);
  66755. }
  66756. }
  66757. else {
  66758. // Need to reset refresh rate of the shadowMap
  66759. if (this._shadowMap) {
  66760. this._shadowMap.resetRefreshCounter();
  66761. }
  66762. }
  66763. };
  66764. ShadowGenerator.prototype._applyFilterValues = function () {
  66765. if (!this._shadowMap) {
  66766. return;
  66767. }
  66768. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66769. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66770. }
  66771. else {
  66772. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66773. }
  66774. };
  66775. /**
  66776. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66777. * @param onCompiled Callback triggered at the and of the effects compilation
  66778. * @param options Sets of optional options forcing the compilation with different modes
  66779. */
  66780. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66781. var _this = this;
  66782. var localOptions = __assign({ useInstances: false }, options);
  66783. var shadowMap = this.getShadowMap();
  66784. if (!shadowMap) {
  66785. if (onCompiled) {
  66786. onCompiled(this);
  66787. }
  66788. return;
  66789. }
  66790. var renderList = shadowMap.renderList;
  66791. if (!renderList) {
  66792. if (onCompiled) {
  66793. onCompiled(this);
  66794. }
  66795. return;
  66796. }
  66797. var subMeshes = new Array();
  66798. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66799. var mesh = renderList_1[_i];
  66800. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66801. }
  66802. if (subMeshes.length === 0) {
  66803. if (onCompiled) {
  66804. onCompiled(this);
  66805. }
  66806. return;
  66807. }
  66808. var currentIndex = 0;
  66809. var checkReady = function () {
  66810. if (!_this._scene || !_this._scene.getEngine()) {
  66811. return;
  66812. }
  66813. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66814. currentIndex++;
  66815. if (currentIndex >= subMeshes.length) {
  66816. if (onCompiled) {
  66817. onCompiled(_this);
  66818. }
  66819. return;
  66820. }
  66821. }
  66822. setTimeout(checkReady, 16);
  66823. };
  66824. checkReady();
  66825. };
  66826. /**
  66827. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66828. * @param options Sets of optional options forcing the compilation with different modes
  66829. * @returns A promise that resolves when the compilation completes
  66830. */
  66831. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66832. var _this = this;
  66833. return new Promise(function (resolve) {
  66834. _this.forceCompilation(function () {
  66835. resolve();
  66836. }, options);
  66837. });
  66838. };
  66839. /**
  66840. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66841. * @param subMesh The submesh we want to render in the shadow map
  66842. * @param useInstances Defines wether will draw in the map using instances
  66843. * @returns true if ready otherwise, false
  66844. */
  66845. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66846. var defines = [];
  66847. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66848. defines.push("#define FLOAT");
  66849. }
  66850. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66851. defines.push("#define ESM");
  66852. }
  66853. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66854. defines.push("#define DEPTHTEXTURE");
  66855. }
  66856. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66857. var mesh = subMesh.getMesh();
  66858. var material = subMesh.getMaterial();
  66859. // Normal bias.
  66860. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66861. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66862. defines.push("#define NORMAL");
  66863. if (mesh.nonUniformScaling) {
  66864. defines.push("#define NONUNIFORMSCALING");
  66865. }
  66866. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66867. defines.push("#define DIRECTIONINLIGHTDATA");
  66868. }
  66869. }
  66870. // Alpha test
  66871. if (material && material.needAlphaTesting()) {
  66872. var alphaTexture = material.getAlphaTestTexture();
  66873. if (alphaTexture) {
  66874. defines.push("#define ALPHATEST");
  66875. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66876. attribs.push(BABYLON.VertexBuffer.UVKind);
  66877. defines.push("#define UV1");
  66878. }
  66879. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66880. if (alphaTexture.coordinatesIndex === 1) {
  66881. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66882. defines.push("#define UV2");
  66883. }
  66884. }
  66885. }
  66886. }
  66887. // Bones
  66888. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66891. if (mesh.numBoneInfluencers > 4) {
  66892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66894. }
  66895. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66896. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66897. }
  66898. else {
  66899. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66900. }
  66901. // Morph targets
  66902. var manager = mesh.morphTargetManager;
  66903. var morphInfluencers = 0;
  66904. if (manager) {
  66905. if (manager.numInfluencers > 0) {
  66906. defines.push("#define MORPHTARGETS");
  66907. morphInfluencers = manager.numInfluencers;
  66908. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66909. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66910. }
  66911. }
  66912. // Instances
  66913. if (useInstances) {
  66914. defines.push("#define INSTANCES");
  66915. attribs.push("world0");
  66916. attribs.push("world1");
  66917. attribs.push("world2");
  66918. attribs.push("world3");
  66919. }
  66920. // Get correct effect
  66921. var join = defines.join("\n");
  66922. if (this._cachedDefines !== join) {
  66923. this._cachedDefines = join;
  66924. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66925. }
  66926. if (!this._effect.isReady()) {
  66927. return false;
  66928. }
  66929. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66930. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66931. this._initializeBlurRTTAndPostProcesses();
  66932. }
  66933. }
  66934. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66935. return false;
  66936. }
  66937. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66938. return false;
  66939. }
  66940. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66941. return false;
  66942. }
  66943. return true;
  66944. };
  66945. /**
  66946. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66947. * @param defines Defines of the material we want to update
  66948. * @param lightIndex Index of the light in the enabled light list of the material
  66949. */
  66950. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66951. var scene = this._scene;
  66952. var light = this._light;
  66953. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66954. return;
  66955. }
  66956. defines["SHADOW" + lightIndex] = true;
  66957. if (this.useContactHardeningShadow) {
  66958. defines["SHADOWPCSS" + lightIndex] = true;
  66959. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66960. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66961. }
  66962. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66963. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66964. }
  66965. // else default to high.
  66966. }
  66967. if (this.usePercentageCloserFiltering) {
  66968. defines["SHADOWPCF" + lightIndex] = true;
  66969. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66970. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66971. }
  66972. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66973. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66974. }
  66975. // else default to high.
  66976. }
  66977. else if (this.usePoissonSampling) {
  66978. defines["SHADOWPOISSON" + lightIndex] = true;
  66979. }
  66980. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66981. defines["SHADOWESM" + lightIndex] = true;
  66982. }
  66983. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66984. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66985. }
  66986. if (light.needCube()) {
  66987. defines["SHADOWCUBE" + lightIndex] = true;
  66988. }
  66989. };
  66990. /**
  66991. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66992. * defined in the generator but impacting the effect).
  66993. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66994. * @param effect The effect we are binfing the information for
  66995. */
  66996. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66997. var light = this._light;
  66998. var scene = this._scene;
  66999. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67000. return;
  67001. }
  67002. var camera = scene.activeCamera;
  67003. if (!camera) {
  67004. return;
  67005. }
  67006. var shadowMap = this.getShadowMap();
  67007. if (!shadowMap) {
  67008. return;
  67009. }
  67010. if (!light.needCube()) {
  67011. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67012. }
  67013. // Only PCF uses depth stencil texture.
  67014. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67015. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67016. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67017. }
  67018. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67019. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67020. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67021. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67022. }
  67023. else {
  67024. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67025. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67026. }
  67027. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67028. };
  67029. /**
  67030. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67031. * (eq to shadow prjection matrix * light transform matrix)
  67032. * @returns The transform matrix used to create the shadow map
  67033. */
  67034. ShadowGenerator.prototype.getTransformMatrix = function () {
  67035. var scene = this._scene;
  67036. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67037. return this._transformMatrix;
  67038. }
  67039. this._currentRenderID = scene.getRenderId();
  67040. this._currentFaceIndexCache = this._currentFaceIndex;
  67041. var lightPosition = this._light.position;
  67042. if (this._light.computeTransformedInformation()) {
  67043. lightPosition = this._light.transformedPosition;
  67044. }
  67045. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67046. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67047. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67048. }
  67049. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67050. this._cachedPosition.copyFrom(lightPosition);
  67051. this._cachedDirection.copyFrom(this._lightDirection);
  67052. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67053. var shadowMap = this.getShadowMap();
  67054. if (shadowMap) {
  67055. var renderList = shadowMap.renderList;
  67056. if (renderList) {
  67057. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67058. }
  67059. }
  67060. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67061. }
  67062. return this._transformMatrix;
  67063. };
  67064. /**
  67065. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67066. * Cube and 2D textures for instance.
  67067. */
  67068. ShadowGenerator.prototype.recreateShadowMap = function () {
  67069. var shadowMap = this._shadowMap;
  67070. if (!shadowMap) {
  67071. return;
  67072. }
  67073. // Track render list.
  67074. var renderList = shadowMap.renderList;
  67075. // Clean up existing data.
  67076. this._disposeRTTandPostProcesses();
  67077. // Reinitializes.
  67078. this._initializeGenerator();
  67079. // Reaffect the filter to ensure a correct fallback if necessary.
  67080. this.filter = this.filter;
  67081. // Reaffect the filter.
  67082. this._applyFilterValues();
  67083. // Reaffect Render List.
  67084. this._shadowMap.renderList = renderList;
  67085. };
  67086. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67087. if (this._shadowMap2) {
  67088. this._shadowMap2.dispose();
  67089. this._shadowMap2 = null;
  67090. }
  67091. if (this._boxBlurPostprocess) {
  67092. this._boxBlurPostprocess.dispose();
  67093. this._boxBlurPostprocess = null;
  67094. }
  67095. if (this._kernelBlurXPostprocess) {
  67096. this._kernelBlurXPostprocess.dispose();
  67097. this._kernelBlurXPostprocess = null;
  67098. }
  67099. if (this._kernelBlurYPostprocess) {
  67100. this._kernelBlurYPostprocess.dispose();
  67101. this._kernelBlurYPostprocess = null;
  67102. }
  67103. this._blurPostProcesses = [];
  67104. };
  67105. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67106. if (this._shadowMap) {
  67107. this._shadowMap.dispose();
  67108. this._shadowMap = null;
  67109. }
  67110. this._disposeBlurPostProcesses();
  67111. };
  67112. /**
  67113. * Disposes the ShadowGenerator.
  67114. * Returns nothing.
  67115. */
  67116. ShadowGenerator.prototype.dispose = function () {
  67117. this._disposeRTTandPostProcesses();
  67118. if (this._light) {
  67119. this._light._shadowGenerator = null;
  67120. this._light._markMeshesAsLightDirty();
  67121. }
  67122. };
  67123. /**
  67124. * Serializes the shadow generator setup to a json object.
  67125. * @returns The serialized JSON object
  67126. */
  67127. ShadowGenerator.prototype.serialize = function () {
  67128. var serializationObject = {};
  67129. var shadowMap = this.getShadowMap();
  67130. if (!shadowMap) {
  67131. return serializationObject;
  67132. }
  67133. serializationObject.lightId = this._light.id;
  67134. serializationObject.mapSize = shadowMap.getRenderSize();
  67135. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67136. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67137. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67138. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67139. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67140. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67141. serializationObject.depthScale = this.depthScale;
  67142. serializationObject.darkness = this.getDarkness();
  67143. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67144. serializationObject.blurKernel = this.blurKernel;
  67145. serializationObject.blurScale = this.blurScale;
  67146. serializationObject.useKernelBlur = this.useKernelBlur;
  67147. serializationObject.transparencyShadow = this._transparencyShadow;
  67148. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67149. serializationObject.bias = this.bias;
  67150. serializationObject.normalBias = this.normalBias;
  67151. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67152. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67153. serializationObject.filteringQuality = this.filteringQuality;
  67154. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67155. serializationObject.renderList = [];
  67156. if (shadowMap.renderList) {
  67157. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67158. var mesh = shadowMap.renderList[meshIndex];
  67159. serializationObject.renderList.push(mesh.id);
  67160. }
  67161. }
  67162. return serializationObject;
  67163. };
  67164. /**
  67165. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67166. * @param parsedShadowGenerator The JSON object to parse
  67167. * @param scene The scene to create the shadow map for
  67168. * @returns The parsed shadow generator
  67169. */
  67170. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67171. //casting to point light, as light is missing the position attr and typescript complains.
  67172. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67173. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67174. var shadowMap = shadowGenerator.getShadowMap();
  67175. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67176. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67177. meshes.forEach(function (mesh) {
  67178. if (!shadowMap) {
  67179. return;
  67180. }
  67181. if (!shadowMap.renderList) {
  67182. shadowMap.renderList = [];
  67183. }
  67184. shadowMap.renderList.push(mesh);
  67185. });
  67186. }
  67187. if (parsedShadowGenerator.usePoissonSampling) {
  67188. shadowGenerator.usePoissonSampling = true;
  67189. }
  67190. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67191. shadowGenerator.useExponentialShadowMap = true;
  67192. }
  67193. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67194. shadowGenerator.useBlurExponentialShadowMap = true;
  67195. }
  67196. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67197. shadowGenerator.useCloseExponentialShadowMap = true;
  67198. }
  67199. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67200. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67201. }
  67202. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67203. shadowGenerator.usePercentageCloserFiltering = true;
  67204. }
  67205. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67206. shadowGenerator.useContactHardeningShadow = true;
  67207. }
  67208. if (parsedShadowGenerator.filteringQuality) {
  67209. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67210. }
  67211. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67212. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67213. }
  67214. // Backward compat
  67215. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67216. shadowGenerator.useExponentialShadowMap = true;
  67217. }
  67218. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67219. shadowGenerator.useBlurExponentialShadowMap = true;
  67220. }
  67221. if (parsedShadowGenerator.depthScale) {
  67222. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67223. }
  67224. if (parsedShadowGenerator.blurScale) {
  67225. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67226. }
  67227. if (parsedShadowGenerator.blurBoxOffset) {
  67228. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67229. }
  67230. if (parsedShadowGenerator.useKernelBlur) {
  67231. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67232. }
  67233. if (parsedShadowGenerator.blurKernel) {
  67234. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67235. }
  67236. if (parsedShadowGenerator.bias !== undefined) {
  67237. shadowGenerator.bias = parsedShadowGenerator.bias;
  67238. }
  67239. if (parsedShadowGenerator.normalBias !== undefined) {
  67240. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67241. }
  67242. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67243. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67244. }
  67245. if (parsedShadowGenerator.darkness) {
  67246. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67247. }
  67248. if (parsedShadowGenerator.transparencyShadow) {
  67249. shadowGenerator.setTransparencyShadow(true);
  67250. }
  67251. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67252. return shadowGenerator;
  67253. };
  67254. /**
  67255. * Shadow generator mode None: no filtering applied.
  67256. */
  67257. ShadowGenerator.FILTER_NONE = 0;
  67258. /**
  67259. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67260. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67261. */
  67262. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67263. /**
  67264. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67265. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67266. */
  67267. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67268. /**
  67269. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67270. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67271. */
  67272. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67273. /**
  67274. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67275. * edge artifacts on steep falloff.
  67276. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67277. */
  67278. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67279. /**
  67280. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67281. * edge artifacts on steep falloff.
  67282. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67283. */
  67284. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67285. /**
  67286. * Shadow generator mode PCF: Percentage Closer Filtering
  67287. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67288. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67289. */
  67290. ShadowGenerator.FILTER_PCF = 6;
  67291. /**
  67292. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67293. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67294. * Contact Hardening
  67295. */
  67296. ShadowGenerator.FILTER_PCSS = 7;
  67297. /**
  67298. * Reserved for PCF and PCSS
  67299. * Highest Quality.
  67300. *
  67301. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67302. *
  67303. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67304. */
  67305. ShadowGenerator.QUALITY_HIGH = 0;
  67306. /**
  67307. * Reserved for PCF and PCSS
  67308. * Good tradeoff for quality/perf cross devices
  67309. *
  67310. * Execute PCF on a 3*3 kernel.
  67311. *
  67312. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67313. */
  67314. ShadowGenerator.QUALITY_MEDIUM = 1;
  67315. /**
  67316. * Reserved for PCF and PCSS
  67317. * The lowest quality but the fastest.
  67318. *
  67319. * Execute PCF on a 1*1 kernel.
  67320. *
  67321. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67322. */
  67323. ShadowGenerator.QUALITY_LOW = 2;
  67324. return ShadowGenerator;
  67325. }());
  67326. BABYLON.ShadowGenerator = ShadowGenerator;
  67327. })(BABYLON || (BABYLON = {}));
  67328. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67329. var BABYLON;
  67330. (function (BABYLON) {
  67331. var DefaultLoadingScreen = /** @class */ (function () {
  67332. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67333. if (_loadingText === void 0) { _loadingText = ""; }
  67334. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67335. var _this = this;
  67336. this._renderingCanvas = _renderingCanvas;
  67337. this._loadingText = _loadingText;
  67338. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67339. // Resize
  67340. this._resizeLoadingUI = function () {
  67341. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67342. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67343. if (!_this._loadingDiv) {
  67344. return;
  67345. }
  67346. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67347. _this._loadingDiv.style.left = canvasRect.left + "px";
  67348. _this._loadingDiv.style.top = canvasRect.top + "px";
  67349. _this._loadingDiv.style.width = canvasRect.width + "px";
  67350. _this._loadingDiv.style.height = canvasRect.height + "px";
  67351. };
  67352. }
  67353. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67354. if (this._loadingDiv) {
  67355. // Do not add a loading screen if there is already one
  67356. return;
  67357. }
  67358. this._loadingDiv = document.createElement("div");
  67359. this._loadingDiv.id = "babylonjsLoadingDiv";
  67360. this._loadingDiv.style.opacity = "0";
  67361. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67362. this._loadingDiv.style.pointerEvents = "none";
  67363. // Loading text
  67364. this._loadingTextDiv = document.createElement("div");
  67365. this._loadingTextDiv.style.position = "absolute";
  67366. this._loadingTextDiv.style.left = "0";
  67367. this._loadingTextDiv.style.top = "50%";
  67368. this._loadingTextDiv.style.marginTop = "80px";
  67369. this._loadingTextDiv.style.width = "100%";
  67370. this._loadingTextDiv.style.height = "20px";
  67371. this._loadingTextDiv.style.fontFamily = "Arial";
  67372. this._loadingTextDiv.style.fontSize = "14px";
  67373. this._loadingTextDiv.style.color = "white";
  67374. this._loadingTextDiv.style.textAlign = "center";
  67375. this._loadingTextDiv.innerHTML = "Loading";
  67376. this._loadingDiv.appendChild(this._loadingTextDiv);
  67377. //set the predefined text
  67378. this._loadingTextDiv.innerHTML = this._loadingText;
  67379. // Generating keyframes
  67380. var style = document.createElement('style');
  67381. style.type = 'text/css';
  67382. 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 }";
  67383. style.innerHTML = keyFrames;
  67384. document.getElementsByTagName('head')[0].appendChild(style);
  67385. // Loading img
  67386. var imgBack = new Image();
  67387. 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";
  67388. imgBack.style.position = "absolute";
  67389. imgBack.style.left = "50%";
  67390. imgBack.style.top = "50%";
  67391. imgBack.style.marginLeft = "-60px";
  67392. imgBack.style.marginTop = "-60px";
  67393. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67394. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67395. imgBack.style.transformOrigin = "50% 50%";
  67396. imgBack.style.webkitTransformOrigin = "50% 50%";
  67397. this._loadingDiv.appendChild(imgBack);
  67398. this._resizeLoadingUI();
  67399. window.addEventListener("resize", this._resizeLoadingUI);
  67400. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67401. document.body.appendChild(this._loadingDiv);
  67402. this._loadingDiv.style.opacity = "1";
  67403. };
  67404. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67405. var _this = this;
  67406. if (!this._loadingDiv) {
  67407. return;
  67408. }
  67409. var onTransitionEnd = function () {
  67410. if (!_this._loadingDiv) {
  67411. return;
  67412. }
  67413. document.body.removeChild(_this._loadingDiv);
  67414. window.removeEventListener("resize", _this._resizeLoadingUI);
  67415. _this._loadingDiv = null;
  67416. };
  67417. this._loadingDiv.style.opacity = "0";
  67418. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67419. };
  67420. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67421. set: function (text) {
  67422. this._loadingText = text;
  67423. if (this._loadingTextDiv) {
  67424. this._loadingTextDiv.innerHTML = this._loadingText;
  67425. }
  67426. },
  67427. enumerable: true,
  67428. configurable: true
  67429. });
  67430. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67431. get: function () {
  67432. return this._loadingDivBackgroundColor;
  67433. },
  67434. set: function (color) {
  67435. this._loadingDivBackgroundColor = color;
  67436. if (!this._loadingDiv) {
  67437. return;
  67438. }
  67439. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67440. },
  67441. enumerable: true,
  67442. configurable: true
  67443. });
  67444. return DefaultLoadingScreen;
  67445. }());
  67446. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67447. })(BABYLON || (BABYLON = {}));
  67448. //# sourceMappingURL=babylon.loadingScreen.js.map
  67449. var BABYLON;
  67450. (function (BABYLON) {
  67451. var SceneLoaderProgressEvent = /** @class */ (function () {
  67452. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67453. this.lengthComputable = lengthComputable;
  67454. this.loaded = loaded;
  67455. this.total = total;
  67456. }
  67457. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67458. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67459. };
  67460. return SceneLoaderProgressEvent;
  67461. }());
  67462. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67463. var SceneLoader = /** @class */ (function () {
  67464. function SceneLoader() {
  67465. }
  67466. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67467. get: function () {
  67468. return 0;
  67469. },
  67470. enumerable: true,
  67471. configurable: true
  67472. });
  67473. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67474. get: function () {
  67475. return 1;
  67476. },
  67477. enumerable: true,
  67478. configurable: true
  67479. });
  67480. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67481. get: function () {
  67482. return 2;
  67483. },
  67484. enumerable: true,
  67485. configurable: true
  67486. });
  67487. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67488. get: function () {
  67489. return 3;
  67490. },
  67491. enumerable: true,
  67492. configurable: true
  67493. });
  67494. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67495. get: function () {
  67496. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67497. },
  67498. set: function (value) {
  67499. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67500. },
  67501. enumerable: true,
  67502. configurable: true
  67503. });
  67504. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67505. get: function () {
  67506. return SceneLoader._ShowLoadingScreen;
  67507. },
  67508. set: function (value) {
  67509. SceneLoader._ShowLoadingScreen = value;
  67510. },
  67511. enumerable: true,
  67512. configurable: true
  67513. });
  67514. Object.defineProperty(SceneLoader, "loggingLevel", {
  67515. get: function () {
  67516. return SceneLoader._loggingLevel;
  67517. },
  67518. set: function (value) {
  67519. SceneLoader._loggingLevel = value;
  67520. },
  67521. enumerable: true,
  67522. configurable: true
  67523. });
  67524. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67525. get: function () {
  67526. return SceneLoader._CleanBoneMatrixWeights;
  67527. },
  67528. set: function (value) {
  67529. SceneLoader._CleanBoneMatrixWeights = value;
  67530. },
  67531. enumerable: true,
  67532. configurable: true
  67533. });
  67534. SceneLoader._getDefaultPlugin = function () {
  67535. return SceneLoader._registeredPlugins[".babylon"];
  67536. };
  67537. SceneLoader._getPluginForExtension = function (extension) {
  67538. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67539. if (registeredPlugin) {
  67540. return registeredPlugin;
  67541. }
  67542. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67543. return SceneLoader._getDefaultPlugin();
  67544. };
  67545. SceneLoader._getPluginForDirectLoad = function (data) {
  67546. for (var extension in SceneLoader._registeredPlugins) {
  67547. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67548. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67549. return SceneLoader._registeredPlugins[extension];
  67550. }
  67551. }
  67552. return SceneLoader._getDefaultPlugin();
  67553. };
  67554. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67555. if (sceneFilename.name) {
  67556. sceneFilename = sceneFilename.name;
  67557. }
  67558. var queryStringPosition = sceneFilename.indexOf("?");
  67559. if (queryStringPosition !== -1) {
  67560. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67561. }
  67562. var dotPosition = sceneFilename.lastIndexOf(".");
  67563. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67564. return SceneLoader._getPluginForExtension(extension);
  67565. };
  67566. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67567. SceneLoader._getDirectLoad = function (sceneFilename) {
  67568. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67569. return sceneFilename.substr(5);
  67570. }
  67571. return null;
  67572. };
  67573. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67574. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67575. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67576. var plugin;
  67577. if (registeredPlugin.plugin.createPlugin) {
  67578. plugin = registeredPlugin.plugin.createPlugin();
  67579. }
  67580. else {
  67581. plugin = registeredPlugin.plugin;
  67582. }
  67583. var useArrayBuffer = registeredPlugin.isBinary;
  67584. var database;
  67585. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67586. var dataCallback = function (data, responseURL) {
  67587. if (scene.isDisposed) {
  67588. onError("Scene has been disposed");
  67589. return;
  67590. }
  67591. scene.database = database;
  67592. onSuccess(plugin, data, responseURL);
  67593. };
  67594. var request = null;
  67595. var pluginDisposed = false;
  67596. var onDisposeObservable = plugin.onDisposeObservable;
  67597. if (onDisposeObservable) {
  67598. onDisposeObservable.add(function () {
  67599. pluginDisposed = true;
  67600. if (request) {
  67601. request.abort();
  67602. request = null;
  67603. }
  67604. onDispose();
  67605. });
  67606. }
  67607. var manifestChecked = function () {
  67608. if (pluginDisposed) {
  67609. return;
  67610. }
  67611. var url = rootUrl + sceneFilename;
  67612. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67613. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67614. } : undefined, database, useArrayBuffer, function (request, exception) {
  67615. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67616. });
  67617. };
  67618. if (directLoad) {
  67619. dataCallback(directLoad);
  67620. return plugin;
  67621. }
  67622. if (rootUrl.indexOf("file:") === -1) {
  67623. var engine = scene.getEngine();
  67624. var canUseOfflineSupport = engine.enableOfflineSupport;
  67625. if (canUseOfflineSupport) {
  67626. // Also check for exceptions
  67627. var exceptionFound = false;
  67628. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67629. var regex = _a[_i];
  67630. if (regex.test(rootUrl + sceneFilename)) {
  67631. exceptionFound = true;
  67632. break;
  67633. }
  67634. }
  67635. canUseOfflineSupport = !exceptionFound;
  67636. }
  67637. if (canUseOfflineSupport) {
  67638. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67639. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67640. }
  67641. else {
  67642. manifestChecked();
  67643. }
  67644. }
  67645. // Loading file from disk via input file or drag'n'drop
  67646. else {
  67647. var fileOrString = sceneFilename;
  67648. if (fileOrString.name) { // File
  67649. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67650. }
  67651. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67652. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67653. }
  67654. else {
  67655. onError("Unable to find file named " + sceneFilename);
  67656. }
  67657. }
  67658. return plugin;
  67659. };
  67660. // Public functions
  67661. SceneLoader.GetPluginForExtension = function (extension) {
  67662. return SceneLoader._getPluginForExtension(extension).plugin;
  67663. };
  67664. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67665. return !!SceneLoader._registeredPlugins[extension];
  67666. };
  67667. SceneLoader.RegisterPlugin = function (plugin) {
  67668. if (typeof plugin.extensions === "string") {
  67669. var extension = plugin.extensions;
  67670. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67671. plugin: plugin,
  67672. isBinary: false
  67673. };
  67674. }
  67675. else {
  67676. var extensions = plugin.extensions;
  67677. Object.keys(extensions).forEach(function (extension) {
  67678. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67679. plugin: plugin,
  67680. isBinary: extensions[extension].isBinary
  67681. };
  67682. });
  67683. }
  67684. };
  67685. /**
  67686. * Import meshes into a scene
  67687. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67688. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67689. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67690. * @param scene the instance of BABYLON.Scene to append to
  67691. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67692. * @param onProgress a callback with a progress event for each file being loaded
  67693. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67694. * @param pluginExtension the extension used to determine the plugin
  67695. * @returns The loaded plugin
  67696. */
  67697. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67698. if (sceneFilename === void 0) { sceneFilename = ""; }
  67699. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67700. if (onSuccess === void 0) { onSuccess = null; }
  67701. if (onProgress === void 0) { onProgress = null; }
  67702. if (onError === void 0) { onError = null; }
  67703. if (pluginExtension === void 0) { pluginExtension = null; }
  67704. if (!scene) {
  67705. BABYLON.Tools.Error("No scene available to import mesh to");
  67706. return null;
  67707. }
  67708. if (!sceneFilename) {
  67709. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67710. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67711. }
  67712. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67713. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67714. return null;
  67715. }
  67716. var loadingToken = {};
  67717. scene._addPendingData(loadingToken);
  67718. var disposeHandler = function () {
  67719. scene._removePendingData(loadingToken);
  67720. };
  67721. var errorHandler = function (message, exception) {
  67722. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67723. if (onError) {
  67724. onError(scene, errorMessage, exception);
  67725. }
  67726. else {
  67727. BABYLON.Tools.Error(errorMessage);
  67728. // should the exception be thrown?
  67729. }
  67730. disposeHandler();
  67731. };
  67732. var progressHandler = onProgress ? function (event) {
  67733. try {
  67734. onProgress(event);
  67735. }
  67736. catch (e) {
  67737. errorHandler("Error in onProgress callback", e);
  67738. }
  67739. } : undefined;
  67740. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67741. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67742. if (onSuccess) {
  67743. try {
  67744. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67745. }
  67746. catch (e) {
  67747. errorHandler("Error in onSuccess callback", e);
  67748. }
  67749. }
  67750. scene._removePendingData(loadingToken);
  67751. };
  67752. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67753. if (plugin.rewriteRootURL) {
  67754. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67755. }
  67756. if (sceneFilename === "") {
  67757. if (sceneFilename === "") {
  67758. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67759. }
  67760. }
  67761. if (plugin.importMesh) {
  67762. var syncedPlugin = plugin;
  67763. var meshes = new Array();
  67764. var particleSystems = new Array();
  67765. var skeletons = new Array();
  67766. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67767. return;
  67768. }
  67769. scene.loadingPluginName = plugin.name;
  67770. successHandler(meshes, particleSystems, skeletons, []);
  67771. }
  67772. else {
  67773. var asyncedPlugin = plugin;
  67774. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67775. scene.loadingPluginName = plugin.name;
  67776. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67777. }).catch(function (error) {
  67778. errorHandler(error.message, error);
  67779. });
  67780. }
  67781. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67782. };
  67783. /**
  67784. * Import meshes into a scene
  67785. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67786. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67787. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67788. * @param scene the instance of BABYLON.Scene to append to
  67789. * @param onProgress a callback with a progress event for each file being loaded
  67790. * @param pluginExtension the extension used to determine the plugin
  67791. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67792. */
  67793. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67794. if (sceneFilename === void 0) { sceneFilename = ""; }
  67795. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67796. if (onProgress === void 0) { onProgress = null; }
  67797. if (pluginExtension === void 0) { pluginExtension = null; }
  67798. return new Promise(function (resolve, reject) {
  67799. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67800. resolve({
  67801. meshes: meshes,
  67802. particleSystems: particleSystems,
  67803. skeletons: skeletons,
  67804. animationGroups: animationGroups
  67805. });
  67806. }, onProgress, function (scene, message, exception) {
  67807. reject(exception || new Error(message));
  67808. }, pluginExtension);
  67809. });
  67810. };
  67811. /**
  67812. * Load a scene
  67813. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67814. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67815. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67816. * @param onSuccess a callback with the scene when import succeeds
  67817. * @param onProgress a callback with a progress event for each file being loaded
  67818. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67819. * @param pluginExtension the extension used to determine the plugin
  67820. * @returns The loaded plugin
  67821. */
  67822. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67823. if (onSuccess === void 0) { onSuccess = null; }
  67824. if (onProgress === void 0) { onProgress = null; }
  67825. if (onError === void 0) { onError = null; }
  67826. if (pluginExtension === void 0) { pluginExtension = null; }
  67827. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67828. };
  67829. /**
  67830. * Load a scene
  67831. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67832. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67833. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67834. * @param onProgress a callback with a progress event for each file being loaded
  67835. * @param pluginExtension the extension used to determine the plugin
  67836. * @returns The loaded scene
  67837. */
  67838. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67839. if (onProgress === void 0) { onProgress = null; }
  67840. if (pluginExtension === void 0) { pluginExtension = null; }
  67841. return new Promise(function (resolve, reject) {
  67842. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67843. resolve(scene);
  67844. }, onProgress, function (scene, message, exception) {
  67845. reject(exception || new Error(message));
  67846. }, pluginExtension);
  67847. });
  67848. };
  67849. /**
  67850. * Append a scene
  67851. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67852. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67853. * @param scene is the instance of BABYLON.Scene to append to
  67854. * @param onSuccess a callback with the scene when import succeeds
  67855. * @param onProgress a callback with a progress event for each file being loaded
  67856. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67857. * @param pluginExtension the extension used to determine the plugin
  67858. * @returns The loaded plugin
  67859. */
  67860. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67861. if (sceneFilename === void 0) { sceneFilename = ""; }
  67862. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67863. if (onSuccess === void 0) { onSuccess = null; }
  67864. if (onProgress === void 0) { onProgress = null; }
  67865. if (onError === void 0) { onError = null; }
  67866. if (pluginExtension === void 0) { pluginExtension = null; }
  67867. if (!scene) {
  67868. BABYLON.Tools.Error("No scene available to append to");
  67869. return null;
  67870. }
  67871. if (!sceneFilename) {
  67872. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67873. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67874. }
  67875. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67876. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67877. return null;
  67878. }
  67879. if (SceneLoader.ShowLoadingScreen) {
  67880. scene.getEngine().displayLoadingUI();
  67881. }
  67882. var loadingToken = {};
  67883. scene._addPendingData(loadingToken);
  67884. var disposeHandler = function () {
  67885. scene._removePendingData(loadingToken);
  67886. scene.getEngine().hideLoadingUI();
  67887. };
  67888. var errorHandler = function (message, exception) {
  67889. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67890. if (onError) {
  67891. onError(scene, errorMessage, exception);
  67892. }
  67893. else {
  67894. BABYLON.Tools.Error(errorMessage);
  67895. // should the exception be thrown?
  67896. }
  67897. disposeHandler();
  67898. };
  67899. var progressHandler = onProgress ? function (event) {
  67900. try {
  67901. onProgress(event);
  67902. }
  67903. catch (e) {
  67904. errorHandler("Error in onProgress callback", e);
  67905. }
  67906. } : undefined;
  67907. var successHandler = function () {
  67908. if (onSuccess) {
  67909. try {
  67910. onSuccess(scene);
  67911. }
  67912. catch (e) {
  67913. errorHandler("Error in onSuccess callback", e);
  67914. }
  67915. }
  67916. scene._removePendingData(loadingToken);
  67917. };
  67918. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67919. if (sceneFilename === "") {
  67920. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67921. }
  67922. if (plugin.load) {
  67923. var syncedPlugin = plugin;
  67924. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67925. return;
  67926. }
  67927. scene.loadingPluginName = plugin.name;
  67928. successHandler();
  67929. }
  67930. else {
  67931. var asyncedPlugin = plugin;
  67932. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67933. scene.loadingPluginName = plugin.name;
  67934. successHandler();
  67935. }).catch(function (error) {
  67936. errorHandler(error.message, error);
  67937. });
  67938. }
  67939. if (SceneLoader.ShowLoadingScreen) {
  67940. scene.executeWhenReady(function () {
  67941. scene.getEngine().hideLoadingUI();
  67942. });
  67943. }
  67944. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67945. };
  67946. /**
  67947. * Append a scene
  67948. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67949. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67950. * @param scene is the instance of BABYLON.Scene to append to
  67951. * @param onProgress a callback with a progress event for each file being loaded
  67952. * @param pluginExtension the extension used to determine the plugin
  67953. * @returns The given scene
  67954. */
  67955. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67956. if (sceneFilename === void 0) { sceneFilename = ""; }
  67957. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67958. if (onProgress === void 0) { onProgress = null; }
  67959. if (pluginExtension === void 0) { pluginExtension = null; }
  67960. return new Promise(function (resolve, reject) {
  67961. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67962. resolve(scene);
  67963. }, onProgress, function (scene, message, exception) {
  67964. reject(exception || new Error(message));
  67965. }, pluginExtension);
  67966. });
  67967. };
  67968. /**
  67969. * Load a scene into an asset container
  67970. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67971. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67972. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67973. * @param onSuccess a callback with the scene when import succeeds
  67974. * @param onProgress a callback with a progress event for each file being loaded
  67975. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67976. * @param pluginExtension the extension used to determine the plugin
  67977. * @returns The loaded plugin
  67978. */
  67979. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67980. if (sceneFilename === void 0) { sceneFilename = ""; }
  67981. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67982. if (onSuccess === void 0) { onSuccess = null; }
  67983. if (onProgress === void 0) { onProgress = null; }
  67984. if (onError === void 0) { onError = null; }
  67985. if (pluginExtension === void 0) { pluginExtension = null; }
  67986. if (!scene) {
  67987. BABYLON.Tools.Error("No scene available to load asset container to");
  67988. return null;
  67989. }
  67990. if (!sceneFilename) {
  67991. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67992. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67993. }
  67994. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67995. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67996. return null;
  67997. }
  67998. var loadingToken = {};
  67999. scene._addPendingData(loadingToken);
  68000. var disposeHandler = function () {
  68001. scene._removePendingData(loadingToken);
  68002. };
  68003. var errorHandler = function (message, exception) {
  68004. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68005. if (onError) {
  68006. onError(scene, errorMessage, exception);
  68007. }
  68008. else {
  68009. BABYLON.Tools.Error(errorMessage);
  68010. // should the exception be thrown?
  68011. }
  68012. disposeHandler();
  68013. };
  68014. var progressHandler = onProgress ? function (event) {
  68015. try {
  68016. onProgress(event);
  68017. }
  68018. catch (e) {
  68019. errorHandler("Error in onProgress callback", e);
  68020. }
  68021. } : undefined;
  68022. var successHandler = function (assets) {
  68023. if (onSuccess) {
  68024. try {
  68025. onSuccess(assets);
  68026. }
  68027. catch (e) {
  68028. errorHandler("Error in onSuccess callback", e);
  68029. }
  68030. }
  68031. scene._removePendingData(loadingToken);
  68032. };
  68033. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68034. if (plugin.loadAssetContainer) {
  68035. var syncedPlugin = plugin;
  68036. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68037. if (!assetContainer) {
  68038. return;
  68039. }
  68040. scene.loadingPluginName = plugin.name;
  68041. successHandler(assetContainer);
  68042. }
  68043. else if (plugin.loadAssetContainerAsync) {
  68044. var asyncedPlugin = plugin;
  68045. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68046. scene.loadingPluginName = plugin.name;
  68047. successHandler(assetContainer);
  68048. }).catch(function (error) {
  68049. errorHandler(error.message, error);
  68050. });
  68051. }
  68052. else {
  68053. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68054. }
  68055. if (SceneLoader.ShowLoadingScreen) {
  68056. scene.executeWhenReady(function () {
  68057. scene.getEngine().hideLoadingUI();
  68058. });
  68059. }
  68060. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68061. };
  68062. /**
  68063. * Load a scene into an asset container
  68064. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68065. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68066. * @param scene is the instance of BABYLON.Scene to append to
  68067. * @param onProgress a callback with a progress event for each file being loaded
  68068. * @param pluginExtension the extension used to determine the plugin
  68069. * @returns The loaded asset container
  68070. */
  68071. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68072. if (sceneFilename === void 0) { sceneFilename = ""; }
  68073. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68074. if (onProgress === void 0) { onProgress = null; }
  68075. if (pluginExtension === void 0) { pluginExtension = null; }
  68076. return new Promise(function (resolve, reject) {
  68077. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68078. resolve(assetContainer);
  68079. }, onProgress, function (scene, message, exception) {
  68080. reject(exception || new Error(message));
  68081. }, pluginExtension);
  68082. });
  68083. };
  68084. // Flags
  68085. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68086. SceneLoader._ShowLoadingScreen = true;
  68087. SceneLoader._CleanBoneMatrixWeights = false;
  68088. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68089. // Members
  68090. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68091. SceneLoader._registeredPlugins = {};
  68092. return SceneLoader;
  68093. }());
  68094. BABYLON.SceneLoader = SceneLoader;
  68095. ;
  68096. })(BABYLON || (BABYLON = {}));
  68097. //# sourceMappingURL=babylon.sceneLoader.js.map
  68098. var BABYLON;
  68099. (function (BABYLON) {
  68100. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68101. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68102. var parsedMaterial = parsedData.materials[index];
  68103. if (parsedMaterial.id === id) {
  68104. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68105. }
  68106. }
  68107. return null;
  68108. };
  68109. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68110. for (var i in names) {
  68111. if (mesh.name === names[i]) {
  68112. hierarchyIds.push(mesh.id);
  68113. return true;
  68114. }
  68115. }
  68116. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68117. hierarchyIds.push(mesh.id);
  68118. return true;
  68119. }
  68120. return false;
  68121. };
  68122. var logOperation = function (operation, producer) {
  68123. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68124. };
  68125. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68126. if (addToScene === void 0) { addToScene = false; }
  68127. var container = new BABYLON.AssetContainer(scene);
  68128. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68129. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68130. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68131. // and avoid problems with multiple concurrent .babylon loads.
  68132. var log = "importScene has failed JSON parse";
  68133. try {
  68134. var parsedData = JSON.parse(data);
  68135. log = "";
  68136. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68137. var index;
  68138. var cache;
  68139. // Lights
  68140. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68141. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68142. var parsedLight = parsedData.lights[index];
  68143. var light = BABYLON.Light.Parse(parsedLight, scene);
  68144. if (light) {
  68145. container.lights.push(light);
  68146. log += (index === 0 ? "\n\tLights:" : "");
  68147. log += "\n\t\t" + light.toString(fullDetails);
  68148. }
  68149. }
  68150. }
  68151. // Animations
  68152. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68153. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68154. var parsedAnimation = parsedData.animations[index];
  68155. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68156. scene.animations.push(animation);
  68157. container.animations.push(animation);
  68158. log += (index === 0 ? "\n\tAnimations:" : "");
  68159. log += "\n\t\t" + animation.toString(fullDetails);
  68160. }
  68161. }
  68162. // Materials
  68163. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68164. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68165. var parsedMaterial = parsedData.materials[index];
  68166. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68167. container.materials.push(mat);
  68168. log += (index === 0 ? "\n\tMaterials:" : "");
  68169. log += "\n\t\t" + mat.toString(fullDetails);
  68170. }
  68171. }
  68172. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68173. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68174. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68175. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68176. container.multiMaterials.push(mmat);
  68177. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68178. log += "\n\t\t" + mmat.toString(fullDetails);
  68179. }
  68180. }
  68181. // Morph targets
  68182. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68183. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68184. var managerData = _a[_i];
  68185. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68186. }
  68187. }
  68188. // Skeletons
  68189. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68190. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68191. var parsedSkeleton = parsedData.skeletons[index];
  68192. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68193. container.skeletons.push(skeleton);
  68194. log += (index === 0 ? "\n\tSkeletons:" : "");
  68195. log += "\n\t\t" + skeleton.toString(fullDetails);
  68196. }
  68197. }
  68198. // Geometries
  68199. var geometries = parsedData.geometries;
  68200. if (geometries !== undefined && geometries !== null) {
  68201. var addedGeometry = new Array();
  68202. // Boxes
  68203. var boxes = geometries.boxes;
  68204. if (boxes !== undefined && boxes !== null) {
  68205. for (index = 0, cache = boxes.length; index < cache; index++) {
  68206. var parsedBox = boxes[index];
  68207. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68208. }
  68209. }
  68210. // Spheres
  68211. var spheres = geometries.spheres;
  68212. if (spheres !== undefined && spheres !== null) {
  68213. for (index = 0, cache = spheres.length; index < cache; index++) {
  68214. var parsedSphere = spheres[index];
  68215. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68216. }
  68217. }
  68218. // Cylinders
  68219. var cylinders = geometries.cylinders;
  68220. if (cylinders !== undefined && cylinders !== null) {
  68221. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68222. var parsedCylinder = cylinders[index];
  68223. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68224. }
  68225. }
  68226. // Toruses
  68227. var toruses = geometries.toruses;
  68228. if (toruses !== undefined && toruses !== null) {
  68229. for (index = 0, cache = toruses.length; index < cache; index++) {
  68230. var parsedTorus = toruses[index];
  68231. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68232. }
  68233. }
  68234. // Grounds
  68235. var grounds = geometries.grounds;
  68236. if (grounds !== undefined && grounds !== null) {
  68237. for (index = 0, cache = grounds.length; index < cache; index++) {
  68238. var parsedGround = grounds[index];
  68239. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68240. }
  68241. }
  68242. // Planes
  68243. var planes = geometries.planes;
  68244. if (planes !== undefined && planes !== null) {
  68245. for (index = 0, cache = planes.length; index < cache; index++) {
  68246. var parsedPlane = planes[index];
  68247. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68248. }
  68249. }
  68250. // TorusKnots
  68251. var torusKnots = geometries.torusKnots;
  68252. if (torusKnots !== undefined && torusKnots !== null) {
  68253. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68254. var parsedTorusKnot = torusKnots[index];
  68255. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68256. }
  68257. }
  68258. // VertexData
  68259. var vertexData = geometries.vertexData;
  68260. if (vertexData !== undefined && vertexData !== null) {
  68261. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68262. var parsedVertexData = vertexData[index];
  68263. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68264. }
  68265. }
  68266. addedGeometry.forEach(function (g) {
  68267. if (g) {
  68268. container.geometries.push(g);
  68269. }
  68270. });
  68271. }
  68272. // Transform nodes
  68273. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68274. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68275. var parsedTransformNode = parsedData.transformNodes[index];
  68276. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68277. container.transformNodes.push(node);
  68278. }
  68279. }
  68280. // Meshes
  68281. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68282. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68283. var parsedMesh = parsedData.meshes[index];
  68284. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68285. container.meshes.push(mesh);
  68286. log += (index === 0 ? "\n\tMeshes:" : "");
  68287. log += "\n\t\t" + mesh.toString(fullDetails);
  68288. }
  68289. }
  68290. // Cameras
  68291. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68292. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68293. var parsedCamera = parsedData.cameras[index];
  68294. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68295. container.cameras.push(camera);
  68296. log += (index === 0 ? "\n\tCameras:" : "");
  68297. log += "\n\t\t" + camera.toString(fullDetails);
  68298. }
  68299. }
  68300. // Browsing all the graph to connect the dots
  68301. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68302. var camera = scene.cameras[index];
  68303. if (camera._waitingParentId) {
  68304. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68305. camera._waitingParentId = null;
  68306. }
  68307. }
  68308. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68309. var light_1 = scene.lights[index];
  68310. if (light_1 && light_1._waitingParentId) {
  68311. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68312. light_1._waitingParentId = null;
  68313. }
  68314. }
  68315. // Sounds
  68316. // TODO: add sound
  68317. var loadedSounds = [];
  68318. var loadedSound;
  68319. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68320. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68321. var parsedSound = parsedData.sounds[index];
  68322. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68323. if (!parsedSound.url)
  68324. parsedSound.url = parsedSound.name;
  68325. if (!loadedSounds[parsedSound.url]) {
  68326. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68327. loadedSounds[parsedSound.url] = loadedSound;
  68328. container.sounds.push(loadedSound);
  68329. }
  68330. else {
  68331. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68332. }
  68333. }
  68334. else {
  68335. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68336. }
  68337. }
  68338. }
  68339. loadedSounds = [];
  68340. // Connect parents & children and parse actions
  68341. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68342. var transformNode = scene.transformNodes[index];
  68343. if (transformNode._waitingParentId) {
  68344. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68345. transformNode._waitingParentId = null;
  68346. }
  68347. }
  68348. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68349. var mesh = scene.meshes[index];
  68350. if (mesh._waitingParentId) {
  68351. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68352. mesh._waitingParentId = null;
  68353. }
  68354. if (mesh._waitingActions) {
  68355. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68356. mesh._waitingActions = null;
  68357. }
  68358. }
  68359. // freeze world matrix application
  68360. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68361. var currentMesh = scene.meshes[index];
  68362. if (currentMesh._waitingFreezeWorldMatrix) {
  68363. currentMesh.freezeWorldMatrix();
  68364. currentMesh._waitingFreezeWorldMatrix = null;
  68365. }
  68366. else {
  68367. currentMesh.computeWorldMatrix(true);
  68368. }
  68369. }
  68370. // Particles Systems
  68371. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68372. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68373. var parsedParticleSystem = parsedData.particleSystems[index];
  68374. if (parsedParticleSystem.activeParticleCount) {
  68375. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68376. container.particleSystems.push(ps);
  68377. }
  68378. else {
  68379. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68380. container.particleSystems.push(ps);
  68381. }
  68382. }
  68383. }
  68384. // Lens flares
  68385. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68386. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68387. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68388. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68389. container.lensFlareSystems.push(lf);
  68390. }
  68391. }
  68392. // Shadows
  68393. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68394. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68395. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68396. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68397. container.shadowGenerators.push(sg);
  68398. }
  68399. }
  68400. // Lights exclusions / inclusions
  68401. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68402. var light_2 = scene.lights[index];
  68403. // Excluded check
  68404. if (light_2._excludedMeshesIds.length > 0) {
  68405. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68406. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68407. if (excludedMesh) {
  68408. light_2.excludedMeshes.push(excludedMesh);
  68409. }
  68410. }
  68411. light_2._excludedMeshesIds = [];
  68412. }
  68413. // Included check
  68414. if (light_2._includedOnlyMeshesIds.length > 0) {
  68415. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68416. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68417. if (includedOnlyMesh) {
  68418. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68419. }
  68420. }
  68421. light_2._includedOnlyMeshesIds = [];
  68422. }
  68423. }
  68424. // Effect layers
  68425. if (parsedData.effectLayers) {
  68426. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68427. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68428. container.effectLayers.push(effectLayer);
  68429. }
  68430. }
  68431. // Actions (scene)
  68432. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68433. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68434. }
  68435. if (!addToScene) {
  68436. container.removeAllFromScene();
  68437. }
  68438. }
  68439. catch (err) {
  68440. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68441. if (onError) {
  68442. onError(msg, err);
  68443. }
  68444. else {
  68445. BABYLON.Tools.Log(msg);
  68446. throw err;
  68447. }
  68448. }
  68449. finally {
  68450. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68451. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68452. }
  68453. }
  68454. return container;
  68455. };
  68456. BABYLON.SceneLoader.RegisterPlugin({
  68457. name: "babylon.js",
  68458. extensions: ".babylon",
  68459. canDirectLoad: function (data) {
  68460. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68461. return true;
  68462. }
  68463. return false;
  68464. },
  68465. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68466. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68467. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68468. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68469. // and avoid problems with multiple concurrent .babylon loads.
  68470. var log = "importMesh has failed JSON parse";
  68471. try {
  68472. var parsedData = JSON.parse(data);
  68473. log = "";
  68474. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68475. if (!meshesNames) {
  68476. meshesNames = null;
  68477. }
  68478. else if (!Array.isArray(meshesNames)) {
  68479. meshesNames = [meshesNames];
  68480. }
  68481. var hierarchyIds = new Array();
  68482. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68483. var loadedSkeletonsIds = [];
  68484. var loadedMaterialsIds = [];
  68485. var index;
  68486. var cache;
  68487. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68488. var parsedMesh = parsedData.meshes[index];
  68489. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68490. if (meshesNames !== null) {
  68491. // Remove found mesh name from list.
  68492. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68493. }
  68494. //Geometry?
  68495. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68496. //does the file contain geometries?
  68497. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68498. //find the correct geometry and add it to the scene
  68499. var found = false;
  68500. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68501. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68502. return;
  68503. }
  68504. else {
  68505. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68506. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68507. switch (geometryType) {
  68508. case "boxes":
  68509. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68510. break;
  68511. case "spheres":
  68512. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68513. break;
  68514. case "cylinders":
  68515. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68516. break;
  68517. case "toruses":
  68518. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68519. break;
  68520. case "grounds":
  68521. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68522. break;
  68523. case "planes":
  68524. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68525. break;
  68526. case "torusKnots":
  68527. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68528. break;
  68529. case "vertexData":
  68530. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68531. break;
  68532. }
  68533. found = true;
  68534. }
  68535. });
  68536. }
  68537. });
  68538. if (found === false) {
  68539. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68540. }
  68541. }
  68542. }
  68543. // Material ?
  68544. if (parsedMesh.materialId) {
  68545. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68546. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68547. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68548. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68549. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68550. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68551. var subMatId = parsedMultiMaterial.materials[matIndex];
  68552. loadedMaterialsIds.push(subMatId);
  68553. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68554. if (mat) {
  68555. log += "\n\tMaterial " + mat.toString(fullDetails);
  68556. }
  68557. }
  68558. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68559. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68560. if (mmat) {
  68561. materialFound = true;
  68562. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68563. }
  68564. break;
  68565. }
  68566. }
  68567. }
  68568. if (materialFound === false) {
  68569. loadedMaterialsIds.push(parsedMesh.materialId);
  68570. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68571. if (!mat) {
  68572. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68573. }
  68574. else {
  68575. log += "\n\tMaterial " + mat.toString(fullDetails);
  68576. }
  68577. }
  68578. }
  68579. // Skeleton ?
  68580. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68581. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68582. if (skeletonAlreadyLoaded === false) {
  68583. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68584. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68585. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68586. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68587. skeletons.push(skeleton);
  68588. loadedSkeletonsIds.push(parsedSkeleton.id);
  68589. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68590. }
  68591. }
  68592. }
  68593. }
  68594. // Morph targets ?
  68595. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68596. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68597. var managerData = _a[_i];
  68598. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68599. }
  68600. }
  68601. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68602. meshes.push(mesh);
  68603. log += "\n\tMesh " + mesh.toString(fullDetails);
  68604. }
  68605. }
  68606. // Connecting parents
  68607. var currentMesh;
  68608. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68609. currentMesh = scene.meshes[index];
  68610. if (currentMesh._waitingParentId) {
  68611. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68612. currentMesh._waitingParentId = null;
  68613. }
  68614. }
  68615. // freeze and compute world matrix application
  68616. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68617. currentMesh = scene.meshes[index];
  68618. if (currentMesh._waitingFreezeWorldMatrix) {
  68619. currentMesh.freezeWorldMatrix();
  68620. currentMesh._waitingFreezeWorldMatrix = null;
  68621. }
  68622. else {
  68623. currentMesh.computeWorldMatrix(true);
  68624. }
  68625. }
  68626. }
  68627. // Particles
  68628. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68629. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68630. var parsedParticleSystem = parsedData.particleSystems[index];
  68631. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68632. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68633. }
  68634. }
  68635. }
  68636. return true;
  68637. }
  68638. catch (err) {
  68639. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68640. if (onError) {
  68641. onError(msg, err);
  68642. }
  68643. else {
  68644. BABYLON.Tools.Log(msg);
  68645. throw err;
  68646. }
  68647. }
  68648. finally {
  68649. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68650. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68651. }
  68652. }
  68653. return false;
  68654. },
  68655. load: function (scene, data, rootUrl, onError) {
  68656. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68657. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68658. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68659. // and avoid problems with multiple concurrent .babylon loads.
  68660. var log = "importScene has failed JSON parse";
  68661. try {
  68662. var parsedData = JSON.parse(data);
  68663. log = "";
  68664. // Scene
  68665. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68666. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68667. }
  68668. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68669. scene.autoClear = parsedData.autoClear;
  68670. }
  68671. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68672. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68673. }
  68674. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68675. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68676. }
  68677. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68678. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68679. }
  68680. // Fog
  68681. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68682. scene.fogMode = parsedData.fogMode;
  68683. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68684. scene.fogStart = parsedData.fogStart;
  68685. scene.fogEnd = parsedData.fogEnd;
  68686. scene.fogDensity = parsedData.fogDensity;
  68687. log += "\tFog mode for scene: ";
  68688. switch (scene.fogMode) {
  68689. // getters not compiling, so using hardcoded
  68690. case 1:
  68691. log += "exp\n";
  68692. break;
  68693. case 2:
  68694. log += "exp2\n";
  68695. break;
  68696. case 3:
  68697. log += "linear\n";
  68698. break;
  68699. }
  68700. }
  68701. //Physics
  68702. if (parsedData.physicsEnabled) {
  68703. var physicsPlugin;
  68704. if (parsedData.physicsEngine === "cannon") {
  68705. physicsPlugin = new BABYLON.CannonJSPlugin();
  68706. }
  68707. else if (parsedData.physicsEngine === "oimo") {
  68708. physicsPlugin = new BABYLON.OimoJSPlugin();
  68709. }
  68710. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68711. //else - default engine, which is currently oimo
  68712. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68713. scene.enablePhysics(physicsGravity, physicsPlugin);
  68714. }
  68715. // Metadata
  68716. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68717. scene.metadata = parsedData.metadata;
  68718. }
  68719. //collisions, if defined. otherwise, default is true
  68720. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68721. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68722. }
  68723. scene.workerCollisions = !!parsedData.workerCollisions;
  68724. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68725. if (!container) {
  68726. return false;
  68727. }
  68728. if (parsedData.autoAnimate) {
  68729. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68730. }
  68731. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68732. scene.setActiveCameraByID(parsedData.activeCameraID);
  68733. }
  68734. // Environment texture
  68735. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68736. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68737. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68738. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68739. if (parsedData.environmentTextureRotationY) {
  68740. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68741. }
  68742. scene.environmentTexture = hdrTexture;
  68743. }
  68744. else {
  68745. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68746. if (parsedData.environmentTextureRotationY) {
  68747. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68748. }
  68749. scene.environmentTexture = cubeTexture;
  68750. }
  68751. if (parsedData.createDefaultSkybox === true) {
  68752. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68753. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68754. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68755. }
  68756. }
  68757. // Finish
  68758. return true;
  68759. }
  68760. catch (err) {
  68761. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68762. if (onError) {
  68763. onError(msg, err);
  68764. }
  68765. else {
  68766. BABYLON.Tools.Log(msg);
  68767. throw err;
  68768. }
  68769. }
  68770. finally {
  68771. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68772. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68773. }
  68774. }
  68775. return false;
  68776. },
  68777. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68778. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68779. return container;
  68780. }
  68781. });
  68782. })(BABYLON || (BABYLON = {}));
  68783. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68784. var BABYLON;
  68785. (function (BABYLON) {
  68786. var FilesInput = /** @class */ (function () {
  68787. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68788. this.onProcessFileCallback = function () { return true; };
  68789. this._engine = engine;
  68790. this._currentScene = scene;
  68791. this._sceneLoadedCallback = sceneLoadedCallback;
  68792. this._progressCallback = progressCallback;
  68793. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68794. this._textureLoadingCallback = textureLoadingCallback;
  68795. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68796. this._onReloadCallback = onReloadCallback;
  68797. this._errorCallback = errorCallback;
  68798. }
  68799. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68800. var _this = this;
  68801. if (elementToMonitor) {
  68802. this._elementToMonitor = elementToMonitor;
  68803. this._dragEnterHandler = function (e) { _this.drag(e); };
  68804. this._dragOverHandler = function (e) { _this.drag(e); };
  68805. this._dropHandler = function (e) { _this.drop(e); };
  68806. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68807. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68808. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68809. }
  68810. };
  68811. FilesInput.prototype.dispose = function () {
  68812. if (!this._elementToMonitor) {
  68813. return;
  68814. }
  68815. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68816. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68817. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68818. };
  68819. FilesInput.prototype.renderFunction = function () {
  68820. if (this._additionalRenderLoopLogicCallback) {
  68821. this._additionalRenderLoopLogicCallback();
  68822. }
  68823. if (this._currentScene) {
  68824. if (this._textureLoadingCallback) {
  68825. var remaining = this._currentScene.getWaitingItemsCount();
  68826. if (remaining > 0) {
  68827. this._textureLoadingCallback(remaining);
  68828. }
  68829. }
  68830. this._currentScene.render();
  68831. }
  68832. };
  68833. FilesInput.prototype.drag = function (e) {
  68834. e.stopPropagation();
  68835. e.preventDefault();
  68836. };
  68837. FilesInput.prototype.drop = function (eventDrop) {
  68838. eventDrop.stopPropagation();
  68839. eventDrop.preventDefault();
  68840. this.loadFiles(eventDrop);
  68841. };
  68842. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68843. var _this = this;
  68844. var reader = folder.createReader();
  68845. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68846. reader.readEntries(function (entries) {
  68847. remaining.count += entries.length;
  68848. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68849. var entry = entries_1[_i];
  68850. if (entry.isFile) {
  68851. entry.file(function (file) {
  68852. file.correctName = relativePath + file.name;
  68853. files.push(file);
  68854. if (--remaining.count === 0) {
  68855. callback();
  68856. }
  68857. });
  68858. }
  68859. else if (entry.isDirectory) {
  68860. _this._traverseFolder(entry, files, remaining, callback);
  68861. }
  68862. }
  68863. if (--remaining.count) {
  68864. callback();
  68865. }
  68866. });
  68867. };
  68868. FilesInput.prototype._processFiles = function (files) {
  68869. for (var i = 0; i < files.length; i++) {
  68870. var name = files[i].correctName.toLowerCase();
  68871. var extension = name.split('.').pop();
  68872. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68873. continue;
  68874. }
  68875. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68876. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68877. this._sceneFileToLoad = files[i];
  68878. }
  68879. else {
  68880. FilesInput.FilesToLoad[name] = files[i];
  68881. }
  68882. }
  68883. };
  68884. FilesInput.prototype.loadFiles = function (event) {
  68885. var _this = this;
  68886. if (this._startingProcessingFilesCallback)
  68887. this._startingProcessingFilesCallback();
  68888. // Handling data transfer via drag'n'drop
  68889. if (event && event.dataTransfer && event.dataTransfer.files) {
  68890. this._filesToLoad = event.dataTransfer.files;
  68891. }
  68892. // Handling files from input files
  68893. if (event && event.target && event.target.files) {
  68894. this._filesToLoad = event.target.files;
  68895. }
  68896. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68897. var files_1 = new Array();
  68898. var folders = [];
  68899. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68900. for (var i = 0; i < this._filesToLoad.length; i++) {
  68901. var fileToLoad = this._filesToLoad[i];
  68902. var name_1 = fileToLoad.name.toLowerCase();
  68903. var entry = void 0;
  68904. fileToLoad.correctName = name_1;
  68905. if (items) {
  68906. var item = items[i];
  68907. if (item.getAsEntry) {
  68908. entry = item.getAsEntry();
  68909. }
  68910. else if (item.webkitGetAsEntry) {
  68911. entry = item.webkitGetAsEntry();
  68912. }
  68913. }
  68914. if (!entry) {
  68915. files_1.push(fileToLoad);
  68916. }
  68917. else {
  68918. if (entry.isDirectory) {
  68919. folders.push(entry);
  68920. }
  68921. else {
  68922. files_1.push(fileToLoad);
  68923. }
  68924. }
  68925. }
  68926. if (folders.length === 0) {
  68927. this._processFiles(files_1);
  68928. this._processReload();
  68929. }
  68930. else {
  68931. var remaining = { count: folders.length };
  68932. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68933. var folder = folders_1[_i];
  68934. this._traverseFolder(folder, files_1, remaining, function () {
  68935. _this._processFiles(files_1);
  68936. if (remaining.count === 0) {
  68937. _this._processReload();
  68938. }
  68939. });
  68940. }
  68941. }
  68942. }
  68943. };
  68944. FilesInput.prototype._processReload = function () {
  68945. if (this._onReloadCallback) {
  68946. this._onReloadCallback(this._sceneFileToLoad);
  68947. }
  68948. else {
  68949. this.reload();
  68950. }
  68951. };
  68952. FilesInput.prototype.reload = function () {
  68953. var _this = this;
  68954. // If a scene file has been provided
  68955. if (this._sceneFileToLoad) {
  68956. if (this._currentScene) {
  68957. if (BABYLON.Tools.errorsCount > 0) {
  68958. BABYLON.Tools.ClearLogCache();
  68959. }
  68960. this._engine.stopRenderLoop();
  68961. }
  68962. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68963. if (_this._progressCallback) {
  68964. _this._progressCallback(progress);
  68965. }
  68966. }).then(function (scene) {
  68967. if (_this._currentScene) {
  68968. _this._currentScene.dispose();
  68969. }
  68970. _this._currentScene = scene;
  68971. if (_this._sceneLoadedCallback) {
  68972. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68973. }
  68974. // Wait for textures and shaders to be ready
  68975. _this._currentScene.executeWhenReady(function () {
  68976. _this._engine.runRenderLoop(function () {
  68977. _this.renderFunction();
  68978. });
  68979. });
  68980. }).catch(function (error) {
  68981. if (_this._errorCallback) {
  68982. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68983. }
  68984. });
  68985. }
  68986. else {
  68987. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68988. }
  68989. };
  68990. FilesInput.FilesToLoad = {};
  68991. return FilesInput;
  68992. }());
  68993. BABYLON.FilesInput = FilesInput;
  68994. })(BABYLON || (BABYLON = {}));
  68995. //# sourceMappingURL=babylon.filesInput.js.map
  68996. var BABYLON;
  68997. (function (BABYLON) {
  68998. /**
  68999. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69000. * The underlying implementation relies on an associative array to ensure the best performances.
  69001. * The value can be anything including 'null' but except 'undefined'
  69002. */
  69003. var StringDictionary = /** @class */ (function () {
  69004. function StringDictionary() {
  69005. this._count = 0;
  69006. this._data = {};
  69007. }
  69008. /**
  69009. * This will clear this dictionary and copy the content from the 'source' one.
  69010. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69011. * @param source the dictionary to take the content from and copy to this dictionary
  69012. */
  69013. StringDictionary.prototype.copyFrom = function (source) {
  69014. var _this = this;
  69015. this.clear();
  69016. source.forEach(function (t, v) { return _this.add(t, v); });
  69017. };
  69018. /**
  69019. * Get a value based from its key
  69020. * @param key the given key to get the matching value from
  69021. * @return the value if found, otherwise undefined is returned
  69022. */
  69023. StringDictionary.prototype.get = function (key) {
  69024. var val = this._data[key];
  69025. if (val !== undefined) {
  69026. return val;
  69027. }
  69028. return undefined;
  69029. };
  69030. /**
  69031. * Get a value from its key or add it if it doesn't exist.
  69032. * This method will ensure you that a given key/data will be present in the dictionary.
  69033. * @param key the given key to get the matching value from
  69034. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69035. * The factory will only be invoked if there's no data for the given key.
  69036. * @return the value corresponding to the key.
  69037. */
  69038. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69039. var val = this.get(key);
  69040. if (val !== undefined) {
  69041. return val;
  69042. }
  69043. val = factory(key);
  69044. if (val) {
  69045. this.add(key, val);
  69046. }
  69047. return val;
  69048. };
  69049. /**
  69050. * Get a value from its key if present in the dictionary otherwise add it
  69051. * @param key the key to get the value from
  69052. * @param val if there's no such key/value pair in the dictionary add it with this value
  69053. * @return the value corresponding to the key
  69054. */
  69055. StringDictionary.prototype.getOrAdd = function (key, val) {
  69056. var curVal = this.get(key);
  69057. if (curVal !== undefined) {
  69058. return curVal;
  69059. }
  69060. this.add(key, val);
  69061. return val;
  69062. };
  69063. /**
  69064. * Check if there's a given key in the dictionary
  69065. * @param key the key to check for
  69066. * @return true if the key is present, false otherwise
  69067. */
  69068. StringDictionary.prototype.contains = function (key) {
  69069. return this._data[key] !== undefined;
  69070. };
  69071. /**
  69072. * Add a new key and its corresponding value
  69073. * @param key the key to add
  69074. * @param value the value corresponding to the key
  69075. * @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
  69076. */
  69077. StringDictionary.prototype.add = function (key, value) {
  69078. if (this._data[key] !== undefined) {
  69079. return false;
  69080. }
  69081. this._data[key] = value;
  69082. ++this._count;
  69083. return true;
  69084. };
  69085. StringDictionary.prototype.set = function (key, value) {
  69086. if (this._data[key] === undefined) {
  69087. return false;
  69088. }
  69089. this._data[key] = value;
  69090. return true;
  69091. };
  69092. /**
  69093. * Get the element of the given key and remove it from the dictionary
  69094. * @param key
  69095. */
  69096. StringDictionary.prototype.getAndRemove = function (key) {
  69097. var val = this.get(key);
  69098. if (val !== undefined) {
  69099. delete this._data[key];
  69100. --this._count;
  69101. return val;
  69102. }
  69103. return null;
  69104. };
  69105. /**
  69106. * Remove a key/value from the dictionary.
  69107. * @param key the key to remove
  69108. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69109. */
  69110. StringDictionary.prototype.remove = function (key) {
  69111. if (this.contains(key)) {
  69112. delete this._data[key];
  69113. --this._count;
  69114. return true;
  69115. }
  69116. return false;
  69117. };
  69118. /**
  69119. * Clear the whole content of the dictionary
  69120. */
  69121. StringDictionary.prototype.clear = function () {
  69122. this._data = {};
  69123. this._count = 0;
  69124. };
  69125. Object.defineProperty(StringDictionary.prototype, "count", {
  69126. get: function () {
  69127. return this._count;
  69128. },
  69129. enumerable: true,
  69130. configurable: true
  69131. });
  69132. /**
  69133. * Execute a callback on each key/val of the dictionary.
  69134. * Note that you can remove any element in this dictionary in the callback implementation
  69135. * @param callback the callback to execute on a given key/value pair
  69136. */
  69137. StringDictionary.prototype.forEach = function (callback) {
  69138. for (var cur in this._data) {
  69139. var val = this._data[cur];
  69140. callback(cur, val);
  69141. }
  69142. };
  69143. /**
  69144. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69145. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69146. * Note that you can remove any element in this dictionary in the callback implementation
  69147. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69148. */
  69149. StringDictionary.prototype.first = function (callback) {
  69150. for (var cur in this._data) {
  69151. var val = this._data[cur];
  69152. var res = callback(cur, val);
  69153. if (res) {
  69154. return res;
  69155. }
  69156. }
  69157. return null;
  69158. };
  69159. return StringDictionary;
  69160. }());
  69161. BABYLON.StringDictionary = StringDictionary;
  69162. })(BABYLON || (BABYLON = {}));
  69163. //# sourceMappingURL=babylon.stringDictionary.js.map
  69164. var BABYLON;
  69165. (function (BABYLON) {
  69166. var Tags = /** @class */ (function () {
  69167. function Tags() {
  69168. }
  69169. Tags.EnableFor = function (obj) {
  69170. obj._tags = obj._tags || {};
  69171. obj.hasTags = function () {
  69172. return Tags.HasTags(obj);
  69173. };
  69174. obj.addTags = function (tagsString) {
  69175. return Tags.AddTagsTo(obj, tagsString);
  69176. };
  69177. obj.removeTags = function (tagsString) {
  69178. return Tags.RemoveTagsFrom(obj, tagsString);
  69179. };
  69180. obj.matchesTagsQuery = function (tagsQuery) {
  69181. return Tags.MatchesQuery(obj, tagsQuery);
  69182. };
  69183. };
  69184. Tags.DisableFor = function (obj) {
  69185. delete obj._tags;
  69186. delete obj.hasTags;
  69187. delete obj.addTags;
  69188. delete obj.removeTags;
  69189. delete obj.matchesTagsQuery;
  69190. };
  69191. Tags.HasTags = function (obj) {
  69192. if (!obj._tags) {
  69193. return false;
  69194. }
  69195. return !BABYLON.Tools.IsEmpty(obj._tags);
  69196. };
  69197. Tags.GetTags = function (obj, asString) {
  69198. if (asString === void 0) { asString = true; }
  69199. if (!obj._tags) {
  69200. return null;
  69201. }
  69202. if (asString) {
  69203. var tagsArray = [];
  69204. for (var tag in obj._tags) {
  69205. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69206. tagsArray.push(tag);
  69207. }
  69208. }
  69209. return tagsArray.join(" ");
  69210. }
  69211. else {
  69212. return obj._tags;
  69213. }
  69214. };
  69215. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69216. // a tag cannot start with '||', '&&', and '!'
  69217. // it cannot contain whitespaces
  69218. Tags.AddTagsTo = function (obj, tagsString) {
  69219. if (!tagsString) {
  69220. return;
  69221. }
  69222. if (typeof tagsString !== "string") {
  69223. return;
  69224. }
  69225. var tags = tagsString.split(" ");
  69226. tags.forEach(function (tag, index, array) {
  69227. Tags._AddTagTo(obj, tag);
  69228. });
  69229. };
  69230. Tags._AddTagTo = function (obj, tag) {
  69231. tag = tag.trim();
  69232. if (tag === "" || tag === "true" || tag === "false") {
  69233. return;
  69234. }
  69235. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69236. return;
  69237. }
  69238. Tags.EnableFor(obj);
  69239. obj._tags[tag] = true;
  69240. };
  69241. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69242. if (!Tags.HasTags(obj)) {
  69243. return;
  69244. }
  69245. var tags = tagsString.split(" ");
  69246. for (var t in tags) {
  69247. Tags._RemoveTagFrom(obj, tags[t]);
  69248. }
  69249. };
  69250. Tags._RemoveTagFrom = function (obj, tag) {
  69251. delete obj._tags[tag];
  69252. };
  69253. Tags.MatchesQuery = function (obj, tagsQuery) {
  69254. if (tagsQuery === undefined) {
  69255. return true;
  69256. }
  69257. if (tagsQuery === "") {
  69258. return Tags.HasTags(obj);
  69259. }
  69260. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69261. };
  69262. return Tags;
  69263. }());
  69264. BABYLON.Tags = Tags;
  69265. })(BABYLON || (BABYLON = {}));
  69266. //# sourceMappingURL=babylon.tags.js.map
  69267. var BABYLON;
  69268. (function (BABYLON) {
  69269. /**
  69270. * Class used to evalaute queries containing `and` and `or` operators
  69271. */
  69272. var AndOrNotEvaluator = /** @class */ (function () {
  69273. function AndOrNotEvaluator() {
  69274. }
  69275. /**
  69276. * Evaluate a query
  69277. * @param query defines the query to evaluate
  69278. * @param evaluateCallback defines the callback used to filter result
  69279. * @returns true if the query matches
  69280. */
  69281. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69282. if (!query.match(/\([^\(\)]*\)/g)) {
  69283. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69284. }
  69285. else {
  69286. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69287. // remove parenthesis
  69288. r = r.slice(1, r.length - 1);
  69289. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69290. });
  69291. }
  69292. if (query === "true") {
  69293. return true;
  69294. }
  69295. if (query === "false") {
  69296. return false;
  69297. }
  69298. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69299. };
  69300. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69301. evaluateCallback = evaluateCallback || (function (r) {
  69302. return r === "true" ? true : false;
  69303. });
  69304. var result;
  69305. var or = parenthesisContent.split("||");
  69306. for (var i in or) {
  69307. if (or.hasOwnProperty(i)) {
  69308. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69309. var and = ori.split("&&");
  69310. if (and.length > 1) {
  69311. for (var j = 0; j < and.length; ++j) {
  69312. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69313. if (andj !== "true" && andj !== "false") {
  69314. if (andj[0] === "!") {
  69315. result = !evaluateCallback(andj.substring(1));
  69316. }
  69317. else {
  69318. result = evaluateCallback(andj);
  69319. }
  69320. }
  69321. else {
  69322. result = andj === "true" ? true : false;
  69323. }
  69324. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69325. ori = "false";
  69326. break;
  69327. }
  69328. }
  69329. }
  69330. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69331. result = true;
  69332. break;
  69333. }
  69334. // result equals false (or undefined)
  69335. if (ori !== "true" && ori !== "false") {
  69336. if (ori[0] === "!") {
  69337. result = !evaluateCallback(ori.substring(1));
  69338. }
  69339. else {
  69340. result = evaluateCallback(ori);
  69341. }
  69342. }
  69343. else {
  69344. result = ori === "true" ? true : false;
  69345. }
  69346. }
  69347. }
  69348. // the whole parenthesis scope is replaced by 'true' or 'false'
  69349. return result ? "true" : "false";
  69350. };
  69351. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69352. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69353. // remove whitespaces
  69354. r = r.replace(/[\s]/g, function () { return ""; });
  69355. return r.length % 2 ? "!" : "";
  69356. });
  69357. booleanString = booleanString.trim();
  69358. if (booleanString === "!true") {
  69359. booleanString = "false";
  69360. }
  69361. else if (booleanString === "!false") {
  69362. booleanString = "true";
  69363. }
  69364. return booleanString;
  69365. };
  69366. return AndOrNotEvaluator;
  69367. }());
  69368. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69369. })(BABYLON || (BABYLON = {}));
  69370. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69371. var BABYLON;
  69372. (function (BABYLON) {
  69373. /**
  69374. * Class used to enable access to IndexedDB
  69375. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69376. */
  69377. var Database = /** @class */ (function () {
  69378. /**
  69379. * Creates a new Database
  69380. * @param urlToScene defines the url to load the scene
  69381. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69382. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69383. */
  69384. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69385. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69386. var _this = this;
  69387. // Handling various flavors of prefixed version of IndexedDB
  69388. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69389. this.callbackManifestChecked = callbackManifestChecked;
  69390. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69391. this.db = null;
  69392. this._enableSceneOffline = false;
  69393. this._enableTexturesOffline = false;
  69394. this.manifestVersionFound = 0;
  69395. this.mustUpdateRessources = false;
  69396. this.hasReachedQuota = false;
  69397. if (!Database.IDBStorageEnabled) {
  69398. this.callbackManifestChecked(true);
  69399. }
  69400. else {
  69401. if (disableManifestCheck) {
  69402. this._enableSceneOffline = true;
  69403. this._enableTexturesOffline = true;
  69404. this.manifestVersionFound = 1;
  69405. BABYLON.Tools.SetImmediate(function () {
  69406. _this.callbackManifestChecked(true);
  69407. });
  69408. }
  69409. else {
  69410. this._checkManifestFile();
  69411. }
  69412. }
  69413. }
  69414. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69415. /**
  69416. * Gets a boolean indicating if scene must be saved in the database
  69417. */
  69418. get: function () {
  69419. return this._enableSceneOffline;
  69420. },
  69421. enumerable: true,
  69422. configurable: true
  69423. });
  69424. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69425. /**
  69426. * Gets a boolean indicating if textures must be saved in the database
  69427. */
  69428. get: function () {
  69429. return this._enableTexturesOffline;
  69430. },
  69431. enumerable: true,
  69432. configurable: true
  69433. });
  69434. Database.prototype._checkManifestFile = function () {
  69435. var _this = this;
  69436. var noManifestFile = function () {
  69437. _this._enableSceneOffline = false;
  69438. _this._enableTexturesOffline = false;
  69439. _this.callbackManifestChecked(false);
  69440. };
  69441. var timeStampUsed = false;
  69442. var manifestURL = this.currentSceneUrl + ".manifest";
  69443. var xhr = new XMLHttpRequest();
  69444. if (navigator.onLine) {
  69445. // Adding a timestamp to by-pass browsers' cache
  69446. timeStampUsed = true;
  69447. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69448. }
  69449. xhr.open("GET", manifestURL, true);
  69450. xhr.addEventListener("load", function () {
  69451. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69452. try {
  69453. var manifestFile = JSON.parse(xhr.response);
  69454. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69455. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69456. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69457. _this.manifestVersionFound = manifestFile.version;
  69458. }
  69459. if (_this.callbackManifestChecked) {
  69460. _this.callbackManifestChecked(true);
  69461. }
  69462. }
  69463. catch (ex) {
  69464. noManifestFile();
  69465. }
  69466. }
  69467. else {
  69468. noManifestFile();
  69469. }
  69470. }, false);
  69471. xhr.addEventListener("error", function (event) {
  69472. if (timeStampUsed) {
  69473. timeStampUsed = false;
  69474. // Let's retry without the timeStamp
  69475. // It could fail when coupled with HTML5 Offline API
  69476. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69477. xhr.open("GET", retryManifestURL, true);
  69478. xhr.send();
  69479. }
  69480. else {
  69481. noManifestFile();
  69482. }
  69483. }, false);
  69484. try {
  69485. xhr.send();
  69486. }
  69487. catch (ex) {
  69488. BABYLON.Tools.Error("Error on XHR send request.");
  69489. this.callbackManifestChecked(false);
  69490. }
  69491. };
  69492. /**
  69493. * Open the database and make it available
  69494. * @param successCallback defines the callback to call on success
  69495. * @param errorCallback defines the callback to call on error
  69496. */
  69497. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69498. var _this = this;
  69499. var handleError = function () {
  69500. _this.isSupported = false;
  69501. if (errorCallback)
  69502. errorCallback();
  69503. };
  69504. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69505. // Your browser doesn't support IndexedDB
  69506. this.isSupported = false;
  69507. if (errorCallback)
  69508. errorCallback();
  69509. }
  69510. else {
  69511. // If the DB hasn't been opened or created yet
  69512. if (!this.db) {
  69513. this.hasReachedQuota = false;
  69514. this.isSupported = true;
  69515. var request = this.idbFactory.open("babylonjs", 1);
  69516. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69517. request.onerror = function (event) {
  69518. handleError();
  69519. };
  69520. // executes when a version change transaction cannot complete due to other active transactions
  69521. request.onblocked = function (event) {
  69522. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69523. handleError();
  69524. };
  69525. // DB has been opened successfully
  69526. request.onsuccess = function (event) {
  69527. _this.db = request.result;
  69528. successCallback();
  69529. };
  69530. // Initialization of the DB. Creating Scenes & Textures stores
  69531. request.onupgradeneeded = function (event) {
  69532. _this.db = (event.target).result;
  69533. if (_this.db) {
  69534. try {
  69535. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69536. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69537. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69538. }
  69539. catch (ex) {
  69540. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69541. handleError();
  69542. }
  69543. }
  69544. };
  69545. }
  69546. // DB has already been created and opened
  69547. else {
  69548. if (successCallback)
  69549. successCallback();
  69550. }
  69551. }
  69552. };
  69553. /**
  69554. * Loads an image from the database
  69555. * @param url defines the url to load from
  69556. * @param image defines the target DOM image
  69557. */
  69558. Database.prototype.loadImageFromDB = function (url, image) {
  69559. var _this = this;
  69560. var completeURL = Database._ReturnFullUrlLocation(url);
  69561. var saveAndLoadImage = function () {
  69562. if (!_this.hasReachedQuota && _this.db !== null) {
  69563. // the texture is not yet in the DB, let's try to save it
  69564. _this._saveImageIntoDBAsync(completeURL, image);
  69565. }
  69566. // If the texture is not in the DB and we've reached the DB quota limit
  69567. // let's load it directly from the web
  69568. else {
  69569. image.src = url;
  69570. }
  69571. };
  69572. if (!this.mustUpdateRessources) {
  69573. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69574. }
  69575. // First time we're download the images or update requested in the manifest file by a version change
  69576. else {
  69577. saveAndLoadImage();
  69578. }
  69579. };
  69580. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69581. if (this.isSupported && this.db !== null) {
  69582. var texture;
  69583. var transaction = this.db.transaction(["textures"]);
  69584. transaction.onabort = function (event) {
  69585. image.src = url;
  69586. };
  69587. transaction.oncomplete = function (event) {
  69588. var blobTextureURL;
  69589. if (texture) {
  69590. var URL = window.URL || window.webkitURL;
  69591. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69592. image.onerror = function () {
  69593. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69594. image.src = url;
  69595. };
  69596. image.src = blobTextureURL;
  69597. }
  69598. else {
  69599. notInDBCallback();
  69600. }
  69601. };
  69602. var getRequest = transaction.objectStore("textures").get(url);
  69603. getRequest.onsuccess = function (event) {
  69604. texture = (event.target).result;
  69605. };
  69606. getRequest.onerror = function (event) {
  69607. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69608. image.src = url;
  69609. };
  69610. }
  69611. else {
  69612. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69613. image.src = url;
  69614. }
  69615. };
  69616. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69617. var _this = this;
  69618. if (this.isSupported) {
  69619. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69620. var generateBlobUrl = function () {
  69621. var blobTextureURL;
  69622. if (blob) {
  69623. var URL = window.URL || window.webkitURL;
  69624. try {
  69625. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69626. }
  69627. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69628. catch (ex) {
  69629. blobTextureURL = URL.createObjectURL(blob);
  69630. }
  69631. }
  69632. if (blobTextureURL) {
  69633. image.src = blobTextureURL;
  69634. }
  69635. };
  69636. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69637. var xhr = new XMLHttpRequest(), blob;
  69638. xhr.open("GET", url, true);
  69639. xhr.responseType = "blob";
  69640. xhr.addEventListener("load", function () {
  69641. if (xhr.status === 200 && _this.db) {
  69642. // Blob as response (XHR2)
  69643. blob = xhr.response;
  69644. var transaction = _this.db.transaction(["textures"], "readwrite");
  69645. // the transaction could abort because of a QuotaExceededError error
  69646. transaction.onabort = function (event) {
  69647. try {
  69648. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69649. var srcElement = (event.srcElement || event.target);
  69650. var error = srcElement.error;
  69651. if (error && error.name === "QuotaExceededError") {
  69652. _this.hasReachedQuota = true;
  69653. }
  69654. }
  69655. catch (ex) { }
  69656. generateBlobUrl();
  69657. };
  69658. transaction.oncomplete = function (event) {
  69659. generateBlobUrl();
  69660. };
  69661. var newTexture = { textureUrl: url, data: blob };
  69662. try {
  69663. // Put the blob into the dabase
  69664. var addRequest = transaction.objectStore("textures").put(newTexture);
  69665. addRequest.onsuccess = function (event) {
  69666. };
  69667. addRequest.onerror = function (event) {
  69668. generateBlobUrl();
  69669. };
  69670. }
  69671. catch (ex) {
  69672. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69673. if (ex.code === 25) {
  69674. Database.IsUASupportingBlobStorage = false;
  69675. }
  69676. image.src = url;
  69677. }
  69678. }
  69679. else {
  69680. image.src = url;
  69681. }
  69682. }, false);
  69683. xhr.addEventListener("error", function (event) {
  69684. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69685. image.src = url;
  69686. }, false);
  69687. xhr.send();
  69688. }
  69689. else {
  69690. image.src = url;
  69691. }
  69692. }
  69693. else {
  69694. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69695. image.src = url;
  69696. }
  69697. };
  69698. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69699. var _this = this;
  69700. var updateVersion = function () {
  69701. // the version is not yet in the DB or we need to update it
  69702. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69703. };
  69704. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69705. };
  69706. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69707. var _this = this;
  69708. if (this.isSupported && this.db) {
  69709. var version;
  69710. try {
  69711. var transaction = this.db.transaction(["versions"]);
  69712. transaction.oncomplete = function (event) {
  69713. if (version) {
  69714. // If the version in the JSON file is different from the version in DB
  69715. if (_this.manifestVersionFound !== version.data) {
  69716. _this.mustUpdateRessources = true;
  69717. updateInDBCallback();
  69718. }
  69719. else {
  69720. callback(version.data);
  69721. }
  69722. }
  69723. // version was not found in DB
  69724. else {
  69725. _this.mustUpdateRessources = true;
  69726. updateInDBCallback();
  69727. }
  69728. };
  69729. transaction.onabort = function (event) {
  69730. callback(-1);
  69731. };
  69732. var getRequest = transaction.objectStore("versions").get(url);
  69733. getRequest.onsuccess = function (event) {
  69734. version = (event.target).result;
  69735. };
  69736. getRequest.onerror = function (event) {
  69737. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69738. callback(-1);
  69739. };
  69740. }
  69741. catch (ex) {
  69742. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69743. callback(-1);
  69744. }
  69745. }
  69746. else {
  69747. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69748. callback(-1);
  69749. }
  69750. };
  69751. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69752. var _this = this;
  69753. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69754. try {
  69755. // Open a transaction to the database
  69756. var transaction = this.db.transaction(["versions"], "readwrite");
  69757. // the transaction could abort because of a QuotaExceededError error
  69758. transaction.onabort = function (event) {
  69759. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69760. var error = event.srcElement['error'];
  69761. if (error && error.name === "QuotaExceededError") {
  69762. _this.hasReachedQuota = true;
  69763. }
  69764. }
  69765. catch (ex) { }
  69766. callback(-1);
  69767. };
  69768. transaction.oncomplete = function (event) {
  69769. callback(_this.manifestVersionFound);
  69770. };
  69771. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69772. // Put the scene into the database
  69773. var addRequest = transaction.objectStore("versions").put(newVersion);
  69774. addRequest.onsuccess = function (event) {
  69775. };
  69776. addRequest.onerror = function (event) {
  69777. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69778. };
  69779. }
  69780. catch (ex) {
  69781. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69782. callback(-1);
  69783. }
  69784. }
  69785. else {
  69786. callback(-1);
  69787. }
  69788. };
  69789. /**
  69790. * Loads a file from database
  69791. * @param url defines the URL to load from
  69792. * @param sceneLoaded defines a callback to call on success
  69793. * @param progressCallBack defines a callback to call when progress changed
  69794. * @param errorCallback defines a callback to call on error
  69795. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69796. */
  69797. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69798. var _this = this;
  69799. var completeUrl = Database._ReturnFullUrlLocation(url);
  69800. var saveAndLoadFile = function () {
  69801. // the scene is not yet in the DB, let's try to save it
  69802. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69803. };
  69804. this._checkVersionFromDB(completeUrl, function (version) {
  69805. if (version !== -1) {
  69806. if (!_this.mustUpdateRessources) {
  69807. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69808. }
  69809. else {
  69810. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69811. }
  69812. }
  69813. else {
  69814. if (errorCallback) {
  69815. errorCallback();
  69816. }
  69817. }
  69818. });
  69819. };
  69820. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69821. if (this.isSupported && this.db) {
  69822. var targetStore;
  69823. if (url.indexOf(".babylon") !== -1) {
  69824. targetStore = "scenes";
  69825. }
  69826. else {
  69827. targetStore = "textures";
  69828. }
  69829. var file;
  69830. var transaction = this.db.transaction([targetStore]);
  69831. transaction.oncomplete = function (event) {
  69832. if (file) {
  69833. callback(file.data);
  69834. }
  69835. // file was not found in DB
  69836. else {
  69837. notInDBCallback();
  69838. }
  69839. };
  69840. transaction.onabort = function (event) {
  69841. notInDBCallback();
  69842. };
  69843. var getRequest = transaction.objectStore(targetStore).get(url);
  69844. getRequest.onsuccess = function (event) {
  69845. file = (event.target).result;
  69846. };
  69847. getRequest.onerror = function (event) {
  69848. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69849. notInDBCallback();
  69850. };
  69851. }
  69852. else {
  69853. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69854. callback();
  69855. }
  69856. };
  69857. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69858. var _this = this;
  69859. if (this.isSupported) {
  69860. var targetStore;
  69861. if (url.indexOf(".babylon") !== -1) {
  69862. targetStore = "scenes";
  69863. }
  69864. else {
  69865. targetStore = "textures";
  69866. }
  69867. // Create XHR
  69868. var xhr = new XMLHttpRequest();
  69869. var fileData;
  69870. xhr.open("GET", url, true);
  69871. if (useArrayBuffer) {
  69872. xhr.responseType = "arraybuffer";
  69873. }
  69874. if (progressCallback) {
  69875. xhr.onprogress = progressCallback;
  69876. }
  69877. xhr.addEventListener("load", function () {
  69878. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69879. // Blob as response (XHR2)
  69880. //fileData = xhr.responseText;
  69881. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69882. if (!_this.hasReachedQuota && _this.db) {
  69883. // Open a transaction to the database
  69884. var transaction = _this.db.transaction([targetStore], "readwrite");
  69885. // the transaction could abort because of a QuotaExceededError error
  69886. transaction.onabort = function (event) {
  69887. try {
  69888. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69889. var error = event.srcElement['error'];
  69890. if (error && error.name === "QuotaExceededError") {
  69891. _this.hasReachedQuota = true;
  69892. }
  69893. }
  69894. catch (ex) { }
  69895. callback(fileData);
  69896. };
  69897. transaction.oncomplete = function (event) {
  69898. callback(fileData);
  69899. };
  69900. var newFile;
  69901. if (targetStore === "scenes") {
  69902. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69903. }
  69904. else {
  69905. newFile = { textureUrl: url, data: fileData };
  69906. }
  69907. try {
  69908. // Put the scene into the database
  69909. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69910. addRequest.onsuccess = function (event) {
  69911. };
  69912. addRequest.onerror = function (event) {
  69913. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69914. };
  69915. }
  69916. catch (ex) {
  69917. callback(fileData);
  69918. }
  69919. }
  69920. else {
  69921. callback(fileData);
  69922. }
  69923. }
  69924. else {
  69925. callback();
  69926. }
  69927. }, false);
  69928. xhr.addEventListener("error", function (event) {
  69929. BABYLON.Tools.Error("error on XHR request.");
  69930. callback();
  69931. }, false);
  69932. xhr.send();
  69933. }
  69934. else {
  69935. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69936. callback();
  69937. }
  69938. };
  69939. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69940. Database.IsUASupportingBlobStorage = true;
  69941. /** Gets a boolean indicating if Database storate is enabled */
  69942. Database.IDBStorageEnabled = true;
  69943. Database._ParseURL = function (url) {
  69944. var a = document.createElement('a');
  69945. a.href = url;
  69946. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69947. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69948. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69949. return absLocation;
  69950. };
  69951. Database._ReturnFullUrlLocation = function (url) {
  69952. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69953. return (Database._ParseURL(window.location.href) + url);
  69954. }
  69955. else {
  69956. return url;
  69957. }
  69958. };
  69959. return Database;
  69960. }());
  69961. BABYLON.Database = Database;
  69962. })(BABYLON || (BABYLON = {}));
  69963. //# sourceMappingURL=babylon.database.js.map
  69964. var BABYLON;
  69965. (function (BABYLON) {
  69966. var FresnelParameters = /** @class */ (function () {
  69967. function FresnelParameters() {
  69968. this._isEnabled = true;
  69969. this.leftColor = BABYLON.Color3.White();
  69970. this.rightColor = BABYLON.Color3.Black();
  69971. this.bias = 0;
  69972. this.power = 1;
  69973. }
  69974. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69975. get: function () {
  69976. return this._isEnabled;
  69977. },
  69978. set: function (value) {
  69979. if (this._isEnabled === value) {
  69980. return;
  69981. }
  69982. this._isEnabled = value;
  69983. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69984. },
  69985. enumerable: true,
  69986. configurable: true
  69987. });
  69988. FresnelParameters.prototype.clone = function () {
  69989. var newFresnelParameters = new FresnelParameters();
  69990. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69991. return newFresnelParameters;
  69992. };
  69993. FresnelParameters.prototype.serialize = function () {
  69994. var serializationObject = {};
  69995. serializationObject.isEnabled = this.isEnabled;
  69996. serializationObject.leftColor = this.leftColor.asArray();
  69997. serializationObject.rightColor = this.rightColor.asArray();
  69998. serializationObject.bias = this.bias;
  69999. serializationObject.power = this.power;
  70000. return serializationObject;
  70001. };
  70002. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70003. var fresnelParameters = new FresnelParameters();
  70004. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70005. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70006. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70007. fresnelParameters.bias = parsedFresnelParameters.bias;
  70008. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70009. return fresnelParameters;
  70010. };
  70011. return FresnelParameters;
  70012. }());
  70013. BABYLON.FresnelParameters = FresnelParameters;
  70014. })(BABYLON || (BABYLON = {}));
  70015. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70016. var BABYLON;
  70017. (function (BABYLON) {
  70018. var MultiMaterial = /** @class */ (function (_super) {
  70019. __extends(MultiMaterial, _super);
  70020. function MultiMaterial(name, scene) {
  70021. var _this = _super.call(this, name, scene, true) || this;
  70022. scene.multiMaterials.push(_this);
  70023. _this.subMaterials = new Array();
  70024. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70025. return _this;
  70026. }
  70027. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70028. get: function () {
  70029. return this._subMaterials;
  70030. },
  70031. set: function (value) {
  70032. this._subMaterials = value;
  70033. this._hookArray(value);
  70034. },
  70035. enumerable: true,
  70036. configurable: true
  70037. });
  70038. MultiMaterial.prototype._hookArray = function (array) {
  70039. var _this = this;
  70040. var oldPush = array.push;
  70041. array.push = function () {
  70042. var items = [];
  70043. for (var _i = 0; _i < arguments.length; _i++) {
  70044. items[_i] = arguments[_i];
  70045. }
  70046. var result = oldPush.apply(array, items);
  70047. _this._markAllSubMeshesAsTexturesDirty();
  70048. return result;
  70049. };
  70050. var oldSplice = array.splice;
  70051. array.splice = function (index, deleteCount) {
  70052. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70053. _this._markAllSubMeshesAsTexturesDirty();
  70054. return deleted;
  70055. };
  70056. };
  70057. // Properties
  70058. MultiMaterial.prototype.getSubMaterial = function (index) {
  70059. if (index < 0 || index >= this.subMaterials.length) {
  70060. return this.getScene().defaultMaterial;
  70061. }
  70062. return this.subMaterials[index];
  70063. };
  70064. MultiMaterial.prototype.getActiveTextures = function () {
  70065. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70066. if (subMaterial) {
  70067. return subMaterial.getActiveTextures();
  70068. }
  70069. else {
  70070. return [];
  70071. }
  70072. }));
  70073. var _a;
  70074. };
  70075. // Methods
  70076. MultiMaterial.prototype.getClassName = function () {
  70077. return "MultiMaterial";
  70078. };
  70079. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70080. for (var index = 0; index < this.subMaterials.length; index++) {
  70081. var subMaterial = this.subMaterials[index];
  70082. if (subMaterial) {
  70083. if (subMaterial.storeEffectOnSubMeshes) {
  70084. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70085. return false;
  70086. }
  70087. continue;
  70088. }
  70089. if (!subMaterial.isReady(mesh)) {
  70090. return false;
  70091. }
  70092. }
  70093. }
  70094. return true;
  70095. };
  70096. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70097. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70098. for (var index = 0; index < this.subMaterials.length; index++) {
  70099. var subMaterial = null;
  70100. var current = this.subMaterials[index];
  70101. if (cloneChildren && current) {
  70102. subMaterial = current.clone(name + "-" + current.name);
  70103. }
  70104. else {
  70105. subMaterial = this.subMaterials[index];
  70106. }
  70107. newMultiMaterial.subMaterials.push(subMaterial);
  70108. }
  70109. return newMultiMaterial;
  70110. };
  70111. MultiMaterial.prototype.serialize = function () {
  70112. var serializationObject = {};
  70113. serializationObject.name = this.name;
  70114. serializationObject.id = this.id;
  70115. if (BABYLON.Tags) {
  70116. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70117. }
  70118. serializationObject.materials = [];
  70119. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70120. var subMat = this.subMaterials[matIndex];
  70121. if (subMat) {
  70122. serializationObject.materials.push(subMat.id);
  70123. }
  70124. else {
  70125. serializationObject.materials.push(null);
  70126. }
  70127. }
  70128. return serializationObject;
  70129. };
  70130. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70131. var scene = this.getScene();
  70132. if (!scene) {
  70133. return;
  70134. }
  70135. var index = scene.multiMaterials.indexOf(this);
  70136. if (index >= 0) {
  70137. scene.multiMaterials.splice(index, 1);
  70138. }
  70139. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70140. };
  70141. return MultiMaterial;
  70142. }(BABYLON.Material));
  70143. BABYLON.MultiMaterial = MultiMaterial;
  70144. })(BABYLON || (BABYLON = {}));
  70145. //# sourceMappingURL=babylon.multiMaterial.js.map
  70146. var BABYLON;
  70147. (function (BABYLON) {
  70148. var FreeCameraTouchInput = /** @class */ (function () {
  70149. function FreeCameraTouchInput() {
  70150. this._offsetX = null;
  70151. this._offsetY = null;
  70152. this._pointerPressed = new Array();
  70153. this.touchAngularSensibility = 200000.0;
  70154. this.touchMoveSensibility = 250.0;
  70155. }
  70156. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70157. var _this = this;
  70158. var previousPosition = null;
  70159. if (this._pointerInput === undefined) {
  70160. this._onLostFocus = function (evt) {
  70161. _this._offsetX = null;
  70162. _this._offsetY = null;
  70163. };
  70164. this._pointerInput = function (p, s) {
  70165. var evt = p.event;
  70166. if (evt.pointerType === "mouse") {
  70167. return;
  70168. }
  70169. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70170. if (!noPreventDefault) {
  70171. evt.preventDefault();
  70172. }
  70173. _this._pointerPressed.push(evt.pointerId);
  70174. if (_this._pointerPressed.length !== 1) {
  70175. return;
  70176. }
  70177. previousPosition = {
  70178. x: evt.clientX,
  70179. y: evt.clientY
  70180. };
  70181. }
  70182. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70183. if (!noPreventDefault) {
  70184. evt.preventDefault();
  70185. }
  70186. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70187. if (index === -1) {
  70188. return;
  70189. }
  70190. _this._pointerPressed.splice(index, 1);
  70191. if (index != 0) {
  70192. return;
  70193. }
  70194. previousPosition = null;
  70195. _this._offsetX = null;
  70196. _this._offsetY = null;
  70197. }
  70198. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70199. if (!noPreventDefault) {
  70200. evt.preventDefault();
  70201. }
  70202. if (!previousPosition) {
  70203. return;
  70204. }
  70205. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70206. if (index != 0) {
  70207. return;
  70208. }
  70209. _this._offsetX = evt.clientX - previousPosition.x;
  70210. _this._offsetY = -(evt.clientY - previousPosition.y);
  70211. }
  70212. };
  70213. }
  70214. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70215. if (this._onLostFocus) {
  70216. element.addEventListener("blur", this._onLostFocus);
  70217. }
  70218. };
  70219. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70220. if (this._pointerInput && element) {
  70221. if (this._observer) {
  70222. this.camera.getScene().onPointerObservable.remove(this._observer);
  70223. this._observer = null;
  70224. }
  70225. if (this._onLostFocus) {
  70226. element.removeEventListener("blur", this._onLostFocus);
  70227. this._onLostFocus = null;
  70228. }
  70229. this._pointerPressed = [];
  70230. this._offsetX = null;
  70231. this._offsetY = null;
  70232. }
  70233. };
  70234. FreeCameraTouchInput.prototype.checkInputs = function () {
  70235. if (this._offsetX && this._offsetY) {
  70236. var camera = this.camera;
  70237. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70238. if (this._pointerPressed.length > 1) {
  70239. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70240. }
  70241. else {
  70242. var speed = camera._computeLocalCameraSpeed();
  70243. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70244. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70245. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70246. }
  70247. }
  70248. };
  70249. FreeCameraTouchInput.prototype.getClassName = function () {
  70250. return "FreeCameraTouchInput";
  70251. };
  70252. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70253. return "touch";
  70254. };
  70255. __decorate([
  70256. BABYLON.serialize()
  70257. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70258. __decorate([
  70259. BABYLON.serialize()
  70260. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70261. return FreeCameraTouchInput;
  70262. }());
  70263. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70264. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70265. })(BABYLON || (BABYLON = {}));
  70266. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70267. var BABYLON;
  70268. (function (BABYLON) {
  70269. // We're mainly based on the logic defined into the FreeCamera code
  70270. var TouchCamera = /** @class */ (function (_super) {
  70271. __extends(TouchCamera, _super);
  70272. //-- end properties for backward compatibility for inputs
  70273. function TouchCamera(name, position, scene) {
  70274. var _this = _super.call(this, name, position, scene) || this;
  70275. _this.inputs.addTouch();
  70276. _this._setupInputs();
  70277. return _this;
  70278. }
  70279. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70280. //-- Begin properties for backward compatibility for inputs
  70281. get: function () {
  70282. var touch = this.inputs.attached["touch"];
  70283. if (touch)
  70284. return touch.touchAngularSensibility;
  70285. return 0;
  70286. },
  70287. set: function (value) {
  70288. var touch = this.inputs.attached["touch"];
  70289. if (touch)
  70290. touch.touchAngularSensibility = value;
  70291. },
  70292. enumerable: true,
  70293. configurable: true
  70294. });
  70295. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70296. get: function () {
  70297. var touch = this.inputs.attached["touch"];
  70298. if (touch)
  70299. return touch.touchMoveSensibility;
  70300. return 0;
  70301. },
  70302. set: function (value) {
  70303. var touch = this.inputs.attached["touch"];
  70304. if (touch)
  70305. touch.touchMoveSensibility = value;
  70306. },
  70307. enumerable: true,
  70308. configurable: true
  70309. });
  70310. TouchCamera.prototype.getClassName = function () {
  70311. return "TouchCamera";
  70312. };
  70313. TouchCamera.prototype._setupInputs = function () {
  70314. var mouse = this.inputs.attached["mouse"];
  70315. if (mouse) {
  70316. mouse.touchEnabled = false;
  70317. }
  70318. };
  70319. return TouchCamera;
  70320. }(BABYLON.FreeCamera));
  70321. BABYLON.TouchCamera = TouchCamera;
  70322. })(BABYLON || (BABYLON = {}));
  70323. //# sourceMappingURL=babylon.touchCamera.js.map
  70324. var BABYLON;
  70325. (function (BABYLON) {
  70326. var ProceduralTexture = /** @class */ (function (_super) {
  70327. __extends(ProceduralTexture, _super);
  70328. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70329. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70330. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70331. if (isCube === void 0) { isCube = false; }
  70332. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70333. _this.isCube = isCube;
  70334. _this.isEnabled = true;
  70335. _this._currentRefreshId = -1;
  70336. _this._refreshRate = 1;
  70337. _this._vertexBuffers = {};
  70338. _this._uniforms = new Array();
  70339. _this._samplers = new Array();
  70340. _this._textures = {};
  70341. _this._floats = {};
  70342. _this._floatsArrays = {};
  70343. _this._colors3 = {};
  70344. _this._colors4 = {};
  70345. _this._vectors2 = {};
  70346. _this._vectors3 = {};
  70347. _this._matrices = {};
  70348. _this._fallbackTextureUsed = false;
  70349. scene.proceduralTextures.push(_this);
  70350. _this._engine = scene.getEngine();
  70351. _this.name = name;
  70352. _this.isRenderTarget = true;
  70353. _this._size = size;
  70354. _this._generateMipMaps = generateMipMaps;
  70355. _this.setFragment(fragment);
  70356. _this._fallbackTexture = fallbackTexture;
  70357. if (isCube) {
  70358. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70359. _this.setFloat("face", 0);
  70360. }
  70361. else {
  70362. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70363. }
  70364. // VBO
  70365. var vertices = [];
  70366. vertices.push(1, 1);
  70367. vertices.push(-1, 1);
  70368. vertices.push(-1, -1);
  70369. vertices.push(1, -1);
  70370. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70371. _this._createIndexBuffer();
  70372. return _this;
  70373. }
  70374. ProceduralTexture.prototype._createIndexBuffer = function () {
  70375. var engine = this._engine;
  70376. // Indices
  70377. var indices = [];
  70378. indices.push(0);
  70379. indices.push(1);
  70380. indices.push(2);
  70381. indices.push(0);
  70382. indices.push(2);
  70383. indices.push(3);
  70384. this._indexBuffer = engine.createIndexBuffer(indices);
  70385. };
  70386. ProceduralTexture.prototype._rebuild = function () {
  70387. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70388. if (vb) {
  70389. vb._rebuild();
  70390. }
  70391. this._createIndexBuffer();
  70392. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70393. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70394. }
  70395. };
  70396. ProceduralTexture.prototype.reset = function () {
  70397. if (this._effect === undefined) {
  70398. return;
  70399. }
  70400. var engine = this._engine;
  70401. engine._releaseEffect(this._effect);
  70402. };
  70403. ProceduralTexture.prototype.isReady = function () {
  70404. var _this = this;
  70405. var engine = this._engine;
  70406. var shaders;
  70407. if (!this._fragment) {
  70408. return false;
  70409. }
  70410. if (this._fallbackTextureUsed) {
  70411. return true;
  70412. }
  70413. if (this._fragment.fragmentElement !== undefined) {
  70414. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70415. }
  70416. else {
  70417. shaders = { vertex: "procedural", fragment: this._fragment };
  70418. }
  70419. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70420. _this.releaseInternalTexture();
  70421. if (_this._fallbackTexture) {
  70422. _this._texture = _this._fallbackTexture._texture;
  70423. if (_this._texture) {
  70424. _this._texture.incrementReferences();
  70425. }
  70426. }
  70427. _this._fallbackTextureUsed = true;
  70428. });
  70429. return this._effect.isReady();
  70430. };
  70431. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70432. this._currentRefreshId = -1;
  70433. };
  70434. ProceduralTexture.prototype.setFragment = function (fragment) {
  70435. this._fragment = fragment;
  70436. };
  70437. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70438. get: function () {
  70439. return this._refreshRate;
  70440. },
  70441. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70442. set: function (value) {
  70443. this._refreshRate = value;
  70444. this.resetRefreshCounter();
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. ProceduralTexture.prototype._shouldRender = function () {
  70450. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70451. return false;
  70452. }
  70453. if (this._fallbackTextureUsed) {
  70454. return false;
  70455. }
  70456. if (this._currentRefreshId === -1) { // At least render once
  70457. this._currentRefreshId = 1;
  70458. return true;
  70459. }
  70460. if (this.refreshRate === this._currentRefreshId) {
  70461. this._currentRefreshId = 1;
  70462. return true;
  70463. }
  70464. this._currentRefreshId++;
  70465. return false;
  70466. };
  70467. ProceduralTexture.prototype.getRenderSize = function () {
  70468. return this._size;
  70469. };
  70470. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70471. if (this._fallbackTextureUsed) {
  70472. return;
  70473. }
  70474. this.releaseInternalTexture();
  70475. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70476. };
  70477. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70478. if (this._uniforms.indexOf(uniformName) === -1) {
  70479. this._uniforms.push(uniformName);
  70480. }
  70481. };
  70482. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70483. if (this._samplers.indexOf(name) === -1) {
  70484. this._samplers.push(name);
  70485. }
  70486. this._textures[name] = texture;
  70487. return this;
  70488. };
  70489. ProceduralTexture.prototype.setFloat = function (name, value) {
  70490. this._checkUniform(name);
  70491. this._floats[name] = value;
  70492. return this;
  70493. };
  70494. ProceduralTexture.prototype.setFloats = function (name, value) {
  70495. this._checkUniform(name);
  70496. this._floatsArrays[name] = value;
  70497. return this;
  70498. };
  70499. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70500. this._checkUniform(name);
  70501. this._colors3[name] = value;
  70502. return this;
  70503. };
  70504. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70505. this._checkUniform(name);
  70506. this._colors4[name] = value;
  70507. return this;
  70508. };
  70509. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70510. this._checkUniform(name);
  70511. this._vectors2[name] = value;
  70512. return this;
  70513. };
  70514. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70515. this._checkUniform(name);
  70516. this._vectors3[name] = value;
  70517. return this;
  70518. };
  70519. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70520. this._checkUniform(name);
  70521. this._matrices[name] = value;
  70522. return this;
  70523. };
  70524. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70525. var scene = this.getScene();
  70526. if (!scene) {
  70527. return;
  70528. }
  70529. var engine = this._engine;
  70530. // Render
  70531. engine.enableEffect(this._effect);
  70532. engine.setState(false);
  70533. // Texture
  70534. for (var name in this._textures) {
  70535. this._effect.setTexture(name, this._textures[name]);
  70536. }
  70537. // Float
  70538. for (name in this._floats) {
  70539. this._effect.setFloat(name, this._floats[name]);
  70540. }
  70541. // Floats
  70542. for (name in this._floatsArrays) {
  70543. this._effect.setArray(name, this._floatsArrays[name]);
  70544. }
  70545. // Color3
  70546. for (name in this._colors3) {
  70547. this._effect.setColor3(name, this._colors3[name]);
  70548. }
  70549. // Color4
  70550. for (name in this._colors4) {
  70551. var color = this._colors4[name];
  70552. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70553. }
  70554. // Vector2
  70555. for (name in this._vectors2) {
  70556. this._effect.setVector2(name, this._vectors2[name]);
  70557. }
  70558. // Vector3
  70559. for (name in this._vectors3) {
  70560. this._effect.setVector3(name, this._vectors3[name]);
  70561. }
  70562. // Matrix
  70563. for (name in this._matrices) {
  70564. this._effect.setMatrix(name, this._matrices[name]);
  70565. }
  70566. if (!this._texture) {
  70567. return;
  70568. }
  70569. if (this.isCube) {
  70570. for (var face = 0; face < 6; face++) {
  70571. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70572. // VBOs
  70573. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70574. this._effect.setFloat("face", face);
  70575. // Clear
  70576. engine.clear(scene.clearColor, true, true, true);
  70577. // Draw order
  70578. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70579. // Mipmaps
  70580. if (face === 5) {
  70581. engine.generateMipMapsForCubemap(this._texture);
  70582. }
  70583. }
  70584. }
  70585. else {
  70586. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70587. // VBOs
  70588. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70589. // Clear
  70590. engine.clear(scene.clearColor, true, true, true);
  70591. // Draw order
  70592. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70593. }
  70594. // Unbind
  70595. engine.unBindFramebuffer(this._texture, this.isCube);
  70596. if (this.onGenerated) {
  70597. this.onGenerated();
  70598. }
  70599. };
  70600. ProceduralTexture.prototype.clone = function () {
  70601. var textureSize = this.getSize();
  70602. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70603. // Base texture
  70604. newTexture.hasAlpha = this.hasAlpha;
  70605. newTexture.level = this.level;
  70606. // RenderTarget Texture
  70607. newTexture.coordinatesMode = this.coordinatesMode;
  70608. return newTexture;
  70609. };
  70610. ProceduralTexture.prototype.dispose = function () {
  70611. var scene = this.getScene();
  70612. if (!scene) {
  70613. return;
  70614. }
  70615. var index = scene.proceduralTextures.indexOf(this);
  70616. if (index >= 0) {
  70617. scene.proceduralTextures.splice(index, 1);
  70618. }
  70619. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70620. if (vertexBuffer) {
  70621. vertexBuffer.dispose();
  70622. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70623. }
  70624. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70625. this._indexBuffer = null;
  70626. }
  70627. _super.prototype.dispose.call(this);
  70628. };
  70629. return ProceduralTexture;
  70630. }(BABYLON.Texture));
  70631. BABYLON.ProceduralTexture = ProceduralTexture;
  70632. })(BABYLON || (BABYLON = {}));
  70633. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70634. var BABYLON;
  70635. (function (BABYLON) {
  70636. var CustomProceduralTexture = /** @class */ (function (_super) {
  70637. __extends(CustomProceduralTexture, _super);
  70638. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70639. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70640. _this._animate = true;
  70641. _this._time = 0;
  70642. _this._texturePath = texturePath;
  70643. //Try to load json
  70644. _this.loadJson(texturePath);
  70645. _this.refreshRate = 1;
  70646. return _this;
  70647. }
  70648. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70649. var _this = this;
  70650. var noConfigFile = function () {
  70651. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70652. try {
  70653. _this.setFragment(_this._texturePath);
  70654. }
  70655. catch (ex) {
  70656. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70657. }
  70658. };
  70659. var configFileUrl = jsonUrl + "/config.json";
  70660. var xhr = new XMLHttpRequest();
  70661. xhr.open("GET", configFileUrl, true);
  70662. xhr.addEventListener("load", function () {
  70663. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70664. try {
  70665. _this._config = JSON.parse(xhr.response);
  70666. _this.updateShaderUniforms();
  70667. _this.updateTextures();
  70668. _this.setFragment(_this._texturePath + "/custom");
  70669. _this._animate = _this._config.animate;
  70670. _this.refreshRate = _this._config.refreshrate;
  70671. }
  70672. catch (ex) {
  70673. noConfigFile();
  70674. }
  70675. }
  70676. else {
  70677. noConfigFile();
  70678. }
  70679. }, false);
  70680. xhr.addEventListener("error", function () {
  70681. noConfigFile();
  70682. }, false);
  70683. try {
  70684. xhr.send();
  70685. }
  70686. catch (ex) {
  70687. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70688. }
  70689. };
  70690. CustomProceduralTexture.prototype.isReady = function () {
  70691. if (!_super.prototype.isReady.call(this)) {
  70692. return false;
  70693. }
  70694. for (var name in this._textures) {
  70695. var texture = this._textures[name];
  70696. if (!texture.isReady()) {
  70697. return false;
  70698. }
  70699. }
  70700. return true;
  70701. };
  70702. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70703. var scene = this.getScene();
  70704. if (this._animate && scene) {
  70705. this._time += scene.getAnimationRatio() * 0.03;
  70706. this.updateShaderUniforms();
  70707. }
  70708. _super.prototype.render.call(this, useCameraPostProcess);
  70709. };
  70710. CustomProceduralTexture.prototype.updateTextures = function () {
  70711. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70712. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70713. }
  70714. };
  70715. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70716. if (this._config) {
  70717. for (var j = 0; j < this._config.uniforms.length; j++) {
  70718. var uniform = this._config.uniforms[j];
  70719. switch (uniform.type) {
  70720. case "float":
  70721. this.setFloat(uniform.name, uniform.value);
  70722. break;
  70723. case "color3":
  70724. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70725. break;
  70726. case "color4":
  70727. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70728. break;
  70729. case "vector2":
  70730. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70731. break;
  70732. case "vector3":
  70733. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70734. break;
  70735. }
  70736. }
  70737. }
  70738. this.setFloat("time", this._time);
  70739. };
  70740. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70741. get: function () {
  70742. return this._animate;
  70743. },
  70744. set: function (value) {
  70745. this._animate = value;
  70746. },
  70747. enumerable: true,
  70748. configurable: true
  70749. });
  70750. return CustomProceduralTexture;
  70751. }(BABYLON.ProceduralTexture));
  70752. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70753. })(BABYLON || (BABYLON = {}));
  70754. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70755. var BABYLON;
  70756. (function (BABYLON) {
  70757. var FreeCameraGamepadInput = /** @class */ (function () {
  70758. function FreeCameraGamepadInput() {
  70759. this.gamepadAngularSensibility = 200;
  70760. this.gamepadMoveSensibility = 40;
  70761. // private members
  70762. this._cameraTransform = BABYLON.Matrix.Identity();
  70763. this._deltaTransform = BABYLON.Vector3.Zero();
  70764. this._vector3 = BABYLON.Vector3.Zero();
  70765. this._vector2 = BABYLON.Vector2.Zero();
  70766. }
  70767. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70768. var _this = this;
  70769. var manager = this.camera.getScene().gamepadManager;
  70770. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70771. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70772. // prioritize XBOX gamepads.
  70773. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70774. _this.gamepad = gamepad;
  70775. }
  70776. }
  70777. });
  70778. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70779. if (_this.gamepad === gamepad) {
  70780. _this.gamepad = null;
  70781. }
  70782. });
  70783. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70784. };
  70785. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70786. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70787. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70788. this.gamepad = null;
  70789. };
  70790. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70791. if (this.gamepad && this.gamepad.leftStick) {
  70792. var camera = this.camera;
  70793. var LSValues = this.gamepad.leftStick;
  70794. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70795. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70796. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70797. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70798. var RSValues = this.gamepad.rightStick;
  70799. if (RSValues) {
  70800. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70801. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70802. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70803. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70804. }
  70805. else {
  70806. RSValues = { x: 0, y: 0 };
  70807. }
  70808. if (!camera.rotationQuaternion) {
  70809. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70810. }
  70811. else {
  70812. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70813. }
  70814. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70815. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70816. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70817. camera.cameraDirection.addInPlace(this._deltaTransform);
  70818. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70819. camera.cameraRotation.addInPlace(this._vector2);
  70820. }
  70821. };
  70822. FreeCameraGamepadInput.prototype.getClassName = function () {
  70823. return "FreeCameraGamepadInput";
  70824. };
  70825. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70826. return "gamepad";
  70827. };
  70828. __decorate([
  70829. BABYLON.serialize()
  70830. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70831. __decorate([
  70832. BABYLON.serialize()
  70833. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70834. return FreeCameraGamepadInput;
  70835. }());
  70836. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70837. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70838. })(BABYLON || (BABYLON = {}));
  70839. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70840. var BABYLON;
  70841. (function (BABYLON) {
  70842. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70843. function ArcRotateCameraGamepadInput() {
  70844. this.gamepadRotationSensibility = 80;
  70845. this.gamepadMoveSensibility = 40;
  70846. }
  70847. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70848. var _this = this;
  70849. var manager = this.camera.getScene().gamepadManager;
  70850. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70851. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70852. // prioritize XBOX gamepads.
  70853. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70854. _this.gamepad = gamepad;
  70855. }
  70856. }
  70857. });
  70858. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70859. if (_this.gamepad === gamepad) {
  70860. _this.gamepad = null;
  70861. }
  70862. });
  70863. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70864. };
  70865. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70866. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70867. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70868. this.gamepad = null;
  70869. };
  70870. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70871. if (this.gamepad) {
  70872. var camera = this.camera;
  70873. var RSValues = this.gamepad.rightStick;
  70874. if (RSValues) {
  70875. if (RSValues.x != 0) {
  70876. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70877. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70878. camera.inertialAlphaOffset += normalizedRX;
  70879. }
  70880. }
  70881. if (RSValues.y != 0) {
  70882. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70883. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70884. camera.inertialBetaOffset += normalizedRY;
  70885. }
  70886. }
  70887. }
  70888. var LSValues = this.gamepad.leftStick;
  70889. if (LSValues && LSValues.y != 0) {
  70890. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70891. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70892. this.camera.inertialRadiusOffset -= normalizedLY;
  70893. }
  70894. }
  70895. }
  70896. };
  70897. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70898. return "ArcRotateCameraGamepadInput";
  70899. };
  70900. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70901. return "gamepad";
  70902. };
  70903. __decorate([
  70904. BABYLON.serialize()
  70905. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70906. __decorate([
  70907. BABYLON.serialize()
  70908. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70909. return ArcRotateCameraGamepadInput;
  70910. }());
  70911. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70912. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70913. })(BABYLON || (BABYLON = {}));
  70914. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70915. var BABYLON;
  70916. (function (BABYLON) {
  70917. var GamepadManager = /** @class */ (function () {
  70918. function GamepadManager(_scene) {
  70919. var _this = this;
  70920. this._scene = _scene;
  70921. this._babylonGamepads = [];
  70922. this._oneGamepadConnected = false;
  70923. this._isMonitoring = false;
  70924. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70925. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70926. this._gamepadEventSupported = false;
  70927. }
  70928. else {
  70929. this._gamepadEventSupported = 'GamepadEvent' in window;
  70930. this._gamepadSupport = (navigator.getGamepads ||
  70931. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70932. }
  70933. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70934. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70935. for (var i in _this._babylonGamepads) {
  70936. var gamepad = _this._babylonGamepads[i];
  70937. if (gamepad && gamepad._isConnected) {
  70938. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70939. }
  70940. }
  70941. });
  70942. this._onGamepadConnectedEvent = function (evt) {
  70943. var gamepad = evt.gamepad;
  70944. if (gamepad.index in _this._babylonGamepads) {
  70945. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70946. return;
  70947. }
  70948. }
  70949. var newGamepad;
  70950. if (_this._babylonGamepads[gamepad.index]) {
  70951. newGamepad = _this._babylonGamepads[gamepad.index];
  70952. newGamepad.browserGamepad = gamepad;
  70953. newGamepad._isConnected = true;
  70954. }
  70955. else {
  70956. newGamepad = _this._addNewGamepad(gamepad);
  70957. }
  70958. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70959. _this._startMonitoringGamepads();
  70960. };
  70961. this._onGamepadDisconnectedEvent = function (evt) {
  70962. var gamepad = evt.gamepad;
  70963. // Remove the gamepad from the list of gamepads to monitor.
  70964. for (var i in _this._babylonGamepads) {
  70965. if (_this._babylonGamepads[i].index === gamepad.index) {
  70966. var disconnectedGamepad = _this._babylonGamepads[i];
  70967. disconnectedGamepad._isConnected = false;
  70968. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70969. break;
  70970. }
  70971. }
  70972. };
  70973. if (this._gamepadSupport) {
  70974. //first add already-connected gamepads
  70975. this._updateGamepadObjects();
  70976. if (this._babylonGamepads.length) {
  70977. this._startMonitoringGamepads();
  70978. }
  70979. // Checking if the gamepad connected event is supported (like in Firefox)
  70980. if (this._gamepadEventSupported) {
  70981. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70982. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70983. }
  70984. else {
  70985. this._startMonitoringGamepads();
  70986. }
  70987. }
  70988. }
  70989. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70990. get: function () {
  70991. return this._babylonGamepads;
  70992. },
  70993. enumerable: true,
  70994. configurable: true
  70995. });
  70996. GamepadManager.prototype.getGamepadByType = function (type) {
  70997. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70998. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70999. var gamepad = _a[_i];
  71000. if (gamepad && gamepad.type === type) {
  71001. return gamepad;
  71002. }
  71003. }
  71004. return null;
  71005. };
  71006. GamepadManager.prototype.dispose = function () {
  71007. if (this._gamepadEventSupported) {
  71008. if (this._onGamepadConnectedEvent) {
  71009. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71010. }
  71011. if (this._onGamepadDisconnectedEvent) {
  71012. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71013. }
  71014. this._onGamepadConnectedEvent = null;
  71015. this._onGamepadDisconnectedEvent = null;
  71016. }
  71017. this._babylonGamepads.forEach(function (gamepad) {
  71018. gamepad.dispose();
  71019. });
  71020. this.onGamepadConnectedObservable.clear();
  71021. this.onGamepadDisconnectedObservable.clear();
  71022. this._oneGamepadConnected = false;
  71023. this._stopMonitoringGamepads();
  71024. this._babylonGamepads = [];
  71025. };
  71026. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71027. if (!this._oneGamepadConnected) {
  71028. this._oneGamepadConnected = true;
  71029. }
  71030. var newGamepad;
  71031. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71032. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71033. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71034. }
  71035. // if pose is supported, use the (WebVR) pose enabled controller
  71036. else if (gamepad.pose) {
  71037. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71038. }
  71039. else {
  71040. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71041. }
  71042. this._babylonGamepads[newGamepad.index] = newGamepad;
  71043. return newGamepad;
  71044. };
  71045. GamepadManager.prototype._startMonitoringGamepads = function () {
  71046. if (!this._isMonitoring) {
  71047. this._isMonitoring = true;
  71048. //back-comp
  71049. if (!this._scene) {
  71050. this._checkGamepadsStatus();
  71051. }
  71052. }
  71053. };
  71054. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71055. this._isMonitoring = false;
  71056. };
  71057. GamepadManager.prototype._checkGamepadsStatus = function () {
  71058. var _this = this;
  71059. // Hack to be compatible Chrome
  71060. this._updateGamepadObjects();
  71061. for (var i in this._babylonGamepads) {
  71062. var gamepad = this._babylonGamepads[i];
  71063. if (!gamepad || !gamepad.isConnected) {
  71064. continue;
  71065. }
  71066. gamepad.update();
  71067. }
  71068. if (this._isMonitoring && !this._scene) {
  71069. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71070. }
  71071. };
  71072. // This function is called only on Chrome, which does not properly support
  71073. // connection/disconnection events and forces you to recopy again the gamepad object
  71074. GamepadManager.prototype._updateGamepadObjects = function () {
  71075. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71076. for (var i = 0; i < gamepads.length; i++) {
  71077. var gamepad = gamepads[i];
  71078. if (gamepad) {
  71079. if (!this._babylonGamepads[gamepad.index]) {
  71080. var newGamepad = this._addNewGamepad(gamepad);
  71081. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71082. }
  71083. else {
  71084. // Forced to copy again this object for Chrome for unknown reason
  71085. this._babylonGamepads[i].browserGamepad = gamepad;
  71086. if (!this._babylonGamepads[i].isConnected) {
  71087. this._babylonGamepads[i]._isConnected = true;
  71088. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71089. }
  71090. }
  71091. }
  71092. }
  71093. };
  71094. return GamepadManager;
  71095. }());
  71096. BABYLON.GamepadManager = GamepadManager;
  71097. })(BABYLON || (BABYLON = {}));
  71098. //# sourceMappingURL=babylon.gamepadManager.js.map
  71099. var BABYLON;
  71100. (function (BABYLON) {
  71101. var StickValues = /** @class */ (function () {
  71102. function StickValues(x, y) {
  71103. this.x = x;
  71104. this.y = y;
  71105. }
  71106. return StickValues;
  71107. }());
  71108. BABYLON.StickValues = StickValues;
  71109. var Gamepad = /** @class */ (function () {
  71110. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71111. if (leftStickX === void 0) { leftStickX = 0; }
  71112. if (leftStickY === void 0) { leftStickY = 1; }
  71113. if (rightStickX === void 0) { rightStickX = 2; }
  71114. if (rightStickY === void 0) { rightStickY = 3; }
  71115. this.id = id;
  71116. this.index = index;
  71117. this.browserGamepad = browserGamepad;
  71118. this._isConnected = true;
  71119. this._invertLeftStickY = false;
  71120. this.type = Gamepad.GAMEPAD;
  71121. this._leftStickAxisX = leftStickX;
  71122. this._leftStickAxisY = leftStickY;
  71123. this._rightStickAxisX = rightStickX;
  71124. this._rightStickAxisY = rightStickY;
  71125. if (this.browserGamepad.axes.length >= 2) {
  71126. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71127. }
  71128. if (this.browserGamepad.axes.length >= 4) {
  71129. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71130. }
  71131. }
  71132. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71133. get: function () {
  71134. return this._isConnected;
  71135. },
  71136. enumerable: true,
  71137. configurable: true
  71138. });
  71139. Gamepad.prototype.onleftstickchanged = function (callback) {
  71140. this._onleftstickchanged = callback;
  71141. };
  71142. Gamepad.prototype.onrightstickchanged = function (callback) {
  71143. this._onrightstickchanged = callback;
  71144. };
  71145. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71146. get: function () {
  71147. return this._leftStick;
  71148. },
  71149. set: function (newValues) {
  71150. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71151. this._onleftstickchanged(newValues);
  71152. }
  71153. this._leftStick = newValues;
  71154. },
  71155. enumerable: true,
  71156. configurable: true
  71157. });
  71158. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71159. get: function () {
  71160. return this._rightStick;
  71161. },
  71162. set: function (newValues) {
  71163. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71164. this._onrightstickchanged(newValues);
  71165. }
  71166. this._rightStick = newValues;
  71167. },
  71168. enumerable: true,
  71169. configurable: true
  71170. });
  71171. Gamepad.prototype.update = function () {
  71172. if (this._leftStick) {
  71173. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71174. if (this._invertLeftStickY) {
  71175. this.leftStick.y *= -1;
  71176. }
  71177. }
  71178. if (this._rightStick) {
  71179. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71180. }
  71181. };
  71182. Gamepad.prototype.dispose = function () {
  71183. };
  71184. Gamepad.GAMEPAD = 0;
  71185. Gamepad.GENERIC = 1;
  71186. Gamepad.XBOX = 2;
  71187. Gamepad.POSE_ENABLED = 3;
  71188. return Gamepad;
  71189. }());
  71190. BABYLON.Gamepad = Gamepad;
  71191. var GenericPad = /** @class */ (function (_super) {
  71192. __extends(GenericPad, _super);
  71193. function GenericPad(id, index, browserGamepad) {
  71194. var _this = _super.call(this, id, index, browserGamepad) || this;
  71195. _this.onButtonDownObservable = new BABYLON.Observable();
  71196. _this.onButtonUpObservable = new BABYLON.Observable();
  71197. _this.type = Gamepad.GENERIC;
  71198. _this._buttons = new Array(browserGamepad.buttons.length);
  71199. return _this;
  71200. }
  71201. GenericPad.prototype.onbuttondown = function (callback) {
  71202. this._onbuttondown = callback;
  71203. };
  71204. GenericPad.prototype.onbuttonup = function (callback) {
  71205. this._onbuttonup = callback;
  71206. };
  71207. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71208. if (newValue !== currentValue) {
  71209. if (newValue === 1) {
  71210. if (this._onbuttondown) {
  71211. this._onbuttondown(buttonIndex);
  71212. }
  71213. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71214. }
  71215. if (newValue === 0) {
  71216. if (this._onbuttonup) {
  71217. this._onbuttonup(buttonIndex);
  71218. }
  71219. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71220. }
  71221. }
  71222. return newValue;
  71223. };
  71224. GenericPad.prototype.update = function () {
  71225. _super.prototype.update.call(this);
  71226. for (var index = 0; index < this._buttons.length; index++) {
  71227. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71228. }
  71229. };
  71230. GenericPad.prototype.dispose = function () {
  71231. _super.prototype.dispose.call(this);
  71232. this.onButtonDownObservable.clear();
  71233. this.onButtonUpObservable.clear();
  71234. };
  71235. return GenericPad;
  71236. }(Gamepad));
  71237. BABYLON.GenericPad = GenericPad;
  71238. })(BABYLON || (BABYLON = {}));
  71239. //# sourceMappingURL=babylon.gamepad.js.map
  71240. var BABYLON;
  71241. (function (BABYLON) {
  71242. /**
  71243. * Defines supported buttons for XBox360 compatible gamepads
  71244. */
  71245. var Xbox360Button;
  71246. (function (Xbox360Button) {
  71247. /** A */
  71248. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71249. /** B */
  71250. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71251. /** X */
  71252. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71253. /** Y */
  71254. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71255. /** Start */
  71256. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71257. /** Back */
  71258. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71259. /** Left button */
  71260. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71261. /** Right button */
  71262. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71263. /** Left stick */
  71264. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71265. /** Right stick */
  71266. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71267. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71268. /** Defines values for XBox360 DPad */
  71269. var Xbox360Dpad;
  71270. (function (Xbox360Dpad) {
  71271. /** Up */
  71272. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71273. /** Down */
  71274. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71275. /** Left */
  71276. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71277. /** Right */
  71278. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71279. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71280. /**
  71281. * Defines a XBox360 gamepad
  71282. */
  71283. var Xbox360Pad = /** @class */ (function (_super) {
  71284. __extends(Xbox360Pad, _super);
  71285. /**
  71286. * Creates a new XBox360 gamepad object
  71287. * @param id defines the id of this gamepad
  71288. * @param index defines its index
  71289. * @param gamepad defines the internal HTML gamepad object
  71290. * @param xboxOne defines if it is a XBox One gamepad
  71291. */
  71292. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71293. if (xboxOne === void 0) { xboxOne = false; }
  71294. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71295. _this._leftTrigger = 0;
  71296. _this._rightTrigger = 0;
  71297. /** Observable raised when a button is pressed */
  71298. _this.onButtonDownObservable = new BABYLON.Observable();
  71299. /** Observable raised when a button is released */
  71300. _this.onButtonUpObservable = new BABYLON.Observable();
  71301. /** Observable raised when a pad is pressed */
  71302. _this.onPadDownObservable = new BABYLON.Observable();
  71303. /** Observable raised when a pad is released */
  71304. _this.onPadUpObservable = new BABYLON.Observable();
  71305. _this._buttonA = 0;
  71306. _this._buttonB = 0;
  71307. _this._buttonX = 0;
  71308. _this._buttonY = 0;
  71309. _this._buttonBack = 0;
  71310. _this._buttonStart = 0;
  71311. _this._buttonLB = 0;
  71312. _this._buttonRB = 0;
  71313. _this._buttonLeftStick = 0;
  71314. _this._buttonRightStick = 0;
  71315. _this._dPadUp = 0;
  71316. _this._dPadDown = 0;
  71317. _this._dPadLeft = 0;
  71318. _this._dPadRight = 0;
  71319. _this._isXboxOnePad = false;
  71320. _this.type = BABYLON.Gamepad.XBOX;
  71321. _this._isXboxOnePad = xboxOne;
  71322. return _this;
  71323. }
  71324. /**
  71325. * Defines the callback to call when left trigger is pressed
  71326. * @param callback defines the callback to use
  71327. */
  71328. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71329. this._onlefttriggerchanged = callback;
  71330. };
  71331. /**
  71332. * Defines the callback to call when right trigger is pressed
  71333. * @param callback defines the callback to use
  71334. */
  71335. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71336. this._onrighttriggerchanged = callback;
  71337. };
  71338. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71339. /**
  71340. * Gets or sets left trigger value
  71341. */
  71342. get: function () {
  71343. return this._leftTrigger;
  71344. },
  71345. set: function (newValue) {
  71346. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71347. this._onlefttriggerchanged(newValue);
  71348. }
  71349. this._leftTrigger = newValue;
  71350. },
  71351. enumerable: true,
  71352. configurable: true
  71353. });
  71354. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71355. /**
  71356. * Gets or sets right trigger value
  71357. */
  71358. get: function () {
  71359. return this._rightTrigger;
  71360. },
  71361. set: function (newValue) {
  71362. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71363. this._onrighttriggerchanged(newValue);
  71364. }
  71365. this._rightTrigger = newValue;
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. /**
  71371. * Defines the callback to call when a button is pressed
  71372. * @param callback defines the callback to use
  71373. */
  71374. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71375. this._onbuttondown = callback;
  71376. };
  71377. /**
  71378. * Defines the callback to call when a button is released
  71379. * @param callback defines the callback to use
  71380. */
  71381. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71382. this._onbuttonup = callback;
  71383. };
  71384. /**
  71385. * Defines the callback to call when a pad is pressed
  71386. * @param callback defines the callback to use
  71387. */
  71388. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71389. this._ondpaddown = callback;
  71390. };
  71391. /**
  71392. * Defines the callback to call when a pad is released
  71393. * @param callback defines the callback to use
  71394. */
  71395. Xbox360Pad.prototype.ondpadup = function (callback) {
  71396. this._ondpadup = callback;
  71397. };
  71398. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71399. if (newValue !== currentValue) {
  71400. if (newValue === 1) {
  71401. if (this._onbuttondown) {
  71402. this._onbuttondown(buttonType);
  71403. }
  71404. this.onButtonDownObservable.notifyObservers(buttonType);
  71405. }
  71406. if (newValue === 0) {
  71407. if (this._onbuttonup) {
  71408. this._onbuttonup(buttonType);
  71409. }
  71410. this.onButtonUpObservable.notifyObservers(buttonType);
  71411. }
  71412. }
  71413. return newValue;
  71414. };
  71415. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71416. if (newValue !== currentValue) {
  71417. if (newValue === 1) {
  71418. if (this._ondpaddown) {
  71419. this._ondpaddown(buttonType);
  71420. }
  71421. this.onPadDownObservable.notifyObservers(buttonType);
  71422. }
  71423. if (newValue === 0) {
  71424. if (this._ondpadup) {
  71425. this._ondpadup(buttonType);
  71426. }
  71427. this.onPadUpObservable.notifyObservers(buttonType);
  71428. }
  71429. }
  71430. return newValue;
  71431. };
  71432. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71433. /** Gets or sets value of A button */
  71434. get: function () {
  71435. return this._buttonA;
  71436. },
  71437. set: function (value) {
  71438. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71439. },
  71440. enumerable: true,
  71441. configurable: true
  71442. });
  71443. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71444. /** Gets or sets value of B button */
  71445. get: function () {
  71446. return this._buttonB;
  71447. },
  71448. set: function (value) {
  71449. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71450. },
  71451. enumerable: true,
  71452. configurable: true
  71453. });
  71454. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71455. /** Gets or sets value of X button */
  71456. get: function () {
  71457. return this._buttonX;
  71458. },
  71459. set: function (value) {
  71460. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71461. },
  71462. enumerable: true,
  71463. configurable: true
  71464. });
  71465. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71466. /** Gets or sets value of Y button */
  71467. get: function () {
  71468. return this._buttonY;
  71469. },
  71470. set: function (value) {
  71471. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71472. },
  71473. enumerable: true,
  71474. configurable: true
  71475. });
  71476. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71477. /** Gets or sets value of Start button */
  71478. get: function () {
  71479. return this._buttonStart;
  71480. },
  71481. set: function (value) {
  71482. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71483. },
  71484. enumerable: true,
  71485. configurable: true
  71486. });
  71487. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71488. /** Gets or sets value of Back button */
  71489. get: function () {
  71490. return this._buttonBack;
  71491. },
  71492. set: function (value) {
  71493. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71494. },
  71495. enumerable: true,
  71496. configurable: true
  71497. });
  71498. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71499. /** Gets or sets value of Left button */
  71500. get: function () {
  71501. return this._buttonLB;
  71502. },
  71503. set: function (value) {
  71504. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71505. },
  71506. enumerable: true,
  71507. configurable: true
  71508. });
  71509. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71510. /** Gets or sets value of Right button */
  71511. get: function () {
  71512. return this._buttonRB;
  71513. },
  71514. set: function (value) {
  71515. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71516. },
  71517. enumerable: true,
  71518. configurable: true
  71519. });
  71520. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71521. /** Gets or sets value of left stick */
  71522. get: function () {
  71523. return this._buttonLeftStick;
  71524. },
  71525. set: function (value) {
  71526. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71527. },
  71528. enumerable: true,
  71529. configurable: true
  71530. });
  71531. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71532. /** Gets or sets value of right stick */
  71533. get: function () {
  71534. return this._buttonRightStick;
  71535. },
  71536. set: function (value) {
  71537. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71538. },
  71539. enumerable: true,
  71540. configurable: true
  71541. });
  71542. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71543. /** Gets or sets value of DPad up */
  71544. get: function () {
  71545. return this._dPadUp;
  71546. },
  71547. set: function (value) {
  71548. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71549. },
  71550. enumerable: true,
  71551. configurable: true
  71552. });
  71553. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71554. /** Gets or sets value of DPad down */
  71555. get: function () {
  71556. return this._dPadDown;
  71557. },
  71558. set: function (value) {
  71559. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71560. },
  71561. enumerable: true,
  71562. configurable: true
  71563. });
  71564. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71565. /** Gets or sets value of DPad left */
  71566. get: function () {
  71567. return this._dPadLeft;
  71568. },
  71569. set: function (value) {
  71570. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71571. },
  71572. enumerable: true,
  71573. configurable: true
  71574. });
  71575. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71576. /** Gets or sets value of DPad right */
  71577. get: function () {
  71578. return this._dPadRight;
  71579. },
  71580. set: function (value) {
  71581. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71582. },
  71583. enumerable: true,
  71584. configurable: true
  71585. });
  71586. /**
  71587. * Force the gamepad to synchronize with device values
  71588. */
  71589. Xbox360Pad.prototype.update = function () {
  71590. _super.prototype.update.call(this);
  71591. if (this._isXboxOnePad) {
  71592. this.buttonA = this.browserGamepad.buttons[0].value;
  71593. this.buttonB = this.browserGamepad.buttons[1].value;
  71594. this.buttonX = this.browserGamepad.buttons[2].value;
  71595. this.buttonY = this.browserGamepad.buttons[3].value;
  71596. this.buttonLB = this.browserGamepad.buttons[4].value;
  71597. this.buttonRB = this.browserGamepad.buttons[5].value;
  71598. this.leftTrigger = this.browserGamepad.axes[2];
  71599. this.rightTrigger = this.browserGamepad.axes[5];
  71600. this.buttonBack = this.browserGamepad.buttons[9].value;
  71601. this.buttonStart = this.browserGamepad.buttons[8].value;
  71602. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71603. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71604. this.dPadUp = this.browserGamepad.buttons[11].value;
  71605. this.dPadDown = this.browserGamepad.buttons[12].value;
  71606. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71607. this.dPadRight = this.browserGamepad.buttons[14].value;
  71608. }
  71609. else {
  71610. this.buttonA = this.browserGamepad.buttons[0].value;
  71611. this.buttonB = this.browserGamepad.buttons[1].value;
  71612. this.buttonX = this.browserGamepad.buttons[2].value;
  71613. this.buttonY = this.browserGamepad.buttons[3].value;
  71614. this.buttonLB = this.browserGamepad.buttons[4].value;
  71615. this.buttonRB = this.browserGamepad.buttons[5].value;
  71616. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71617. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71618. this.buttonBack = this.browserGamepad.buttons[8].value;
  71619. this.buttonStart = this.browserGamepad.buttons[9].value;
  71620. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71621. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71622. this.dPadUp = this.browserGamepad.buttons[12].value;
  71623. this.dPadDown = this.browserGamepad.buttons[13].value;
  71624. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71625. this.dPadRight = this.browserGamepad.buttons[15].value;
  71626. }
  71627. };
  71628. Xbox360Pad.prototype.dispose = function () {
  71629. _super.prototype.dispose.call(this);
  71630. this.onButtonDownObservable.clear();
  71631. this.onButtonUpObservable.clear();
  71632. this.onPadDownObservable.clear();
  71633. this.onPadUpObservable.clear();
  71634. };
  71635. return Xbox360Pad;
  71636. }(BABYLON.Gamepad));
  71637. BABYLON.Xbox360Pad = Xbox360Pad;
  71638. })(BABYLON || (BABYLON = {}));
  71639. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71640. var BABYLON;
  71641. (function (BABYLON) {
  71642. /**
  71643. * Defines the types of pose enabled controllers that are supported
  71644. */
  71645. var PoseEnabledControllerType;
  71646. (function (PoseEnabledControllerType) {
  71647. /**
  71648. * HTC Vive
  71649. */
  71650. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71651. /**
  71652. * Oculus Rift
  71653. */
  71654. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71655. /**
  71656. * Windows mixed reality
  71657. */
  71658. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71659. /**
  71660. * Samsung gear VR
  71661. */
  71662. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71663. /**
  71664. * Google Daydream
  71665. */
  71666. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71667. /**
  71668. * Generic
  71669. */
  71670. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71671. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71672. /**
  71673. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71674. */
  71675. var PoseEnabledControllerHelper = /** @class */ (function () {
  71676. function PoseEnabledControllerHelper() {
  71677. }
  71678. /**
  71679. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71680. * @param vrGamepad the gamepad to initialized
  71681. * @returns a vr controller of the type the gamepad identified as
  71682. */
  71683. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71684. // Oculus Touch
  71685. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71686. return new BABYLON.OculusTouchController(vrGamepad);
  71687. }
  71688. // Windows Mixed Reality controllers
  71689. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71690. return new BABYLON.WindowsMotionController(vrGamepad);
  71691. }
  71692. // HTC Vive
  71693. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71694. return new BABYLON.ViveController(vrGamepad);
  71695. }
  71696. // Samsung/Oculus Gear VR or Oculus Go
  71697. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71698. return new BABYLON.GearVRController(vrGamepad);
  71699. }
  71700. // Google Daydream
  71701. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71702. return new BABYLON.DaydreamController(vrGamepad);
  71703. }
  71704. // Generic
  71705. else {
  71706. return new BABYLON.GenericController(vrGamepad);
  71707. }
  71708. };
  71709. return PoseEnabledControllerHelper;
  71710. }());
  71711. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71712. /**
  71713. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71714. */
  71715. var PoseEnabledController = /** @class */ (function (_super) {
  71716. __extends(PoseEnabledController, _super);
  71717. /**
  71718. * Creates a new PoseEnabledController from a gamepad
  71719. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71720. */
  71721. function PoseEnabledController(browserGamepad) {
  71722. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71723. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71724. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71725. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71726. /**
  71727. * The device position in babylon space
  71728. */
  71729. _this.devicePosition = BABYLON.Vector3.Zero();
  71730. /**
  71731. * The device rotation in babylon space
  71732. */
  71733. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71734. /**
  71735. * The scale factor of the device in babylon space
  71736. */
  71737. _this.deviceScaleFactor = 1;
  71738. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71739. /**
  71740. * Internal, matrix used to convert room space to babylon space
  71741. */
  71742. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71743. /**
  71744. * Node to be used when casting a ray from the controller
  71745. */
  71746. _this._pointingPoseNode = null;
  71747. _this._workingMatrix = BABYLON.Matrix.Identity();
  71748. /**
  71749. * @hidden
  71750. */
  71751. _this._meshAttachedObservable = new BABYLON.Observable();
  71752. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71753. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71754. _this.position = BABYLON.Vector3.Zero();
  71755. _this.rotationQuaternion = new BABYLON.Quaternion();
  71756. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71757. _this._calculatedRotation = new BABYLON.Quaternion();
  71758. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71759. return _this;
  71760. }
  71761. /**
  71762. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71763. */
  71764. PoseEnabledController.prototype.update = function () {
  71765. _super.prototype.update.call(this);
  71766. var pose = this.browserGamepad.pose;
  71767. this.updateFromDevice(pose);
  71768. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71769. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71770. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71771. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71772. if (this._mesh) {
  71773. this._mesh.position.copyFrom(this.devicePosition);
  71774. if (this._mesh.rotationQuaternion) {
  71775. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71776. }
  71777. }
  71778. };
  71779. /**
  71780. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71781. * @param poseData raw pose fromthe device
  71782. */
  71783. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71784. if (poseData) {
  71785. this.rawPose = poseData;
  71786. if (poseData.position) {
  71787. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71788. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71789. this._deviceRoomPosition.z *= -1;
  71790. }
  71791. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71792. this._calculatedPosition.addInPlace(this.position);
  71793. }
  71794. var pose = this.rawPose;
  71795. if (poseData.orientation && pose.orientation) {
  71796. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71797. if (this._mesh) {
  71798. if (this._mesh.getScene().useRightHandedSystem) {
  71799. this._deviceRoomRotationQuaternion.z *= -1;
  71800. this._deviceRoomRotationQuaternion.w *= -1;
  71801. }
  71802. else {
  71803. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71804. }
  71805. }
  71806. // if the camera is set, rotate to the camera's rotation
  71807. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71808. }
  71809. }
  71810. };
  71811. /**
  71812. * Attaches a mesh to the controller
  71813. * @param mesh the mesh to be attached
  71814. */
  71815. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71816. if (this._mesh) {
  71817. this._mesh.parent = null;
  71818. }
  71819. this._mesh = mesh;
  71820. if (this._poseControlledCamera) {
  71821. this._mesh.parent = this._poseControlledCamera;
  71822. }
  71823. if (!this._mesh.rotationQuaternion) {
  71824. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71825. }
  71826. this._meshAttachedObservable.notifyObservers(mesh);
  71827. };
  71828. /**
  71829. * Attaches the controllers mesh to a camera
  71830. * @param camera the camera the mesh should be attached to
  71831. */
  71832. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71833. this._poseControlledCamera = camera;
  71834. if (this._mesh) {
  71835. this._mesh.parent = this._poseControlledCamera;
  71836. }
  71837. };
  71838. /**
  71839. * Disposes of the controller
  71840. */
  71841. PoseEnabledController.prototype.dispose = function () {
  71842. if (this._mesh) {
  71843. this._mesh.dispose();
  71844. }
  71845. this._mesh = null;
  71846. _super.prototype.dispose.call(this);
  71847. };
  71848. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71849. /**
  71850. * The mesh that is attached to the controller
  71851. */
  71852. get: function () {
  71853. return this._mesh;
  71854. },
  71855. enumerable: true,
  71856. configurable: true
  71857. });
  71858. /**
  71859. * Gets the ray of the controller in the direction the controller is pointing
  71860. * @param length the length the resulting ray should be
  71861. * @returns a ray in the direction the controller is pointing
  71862. */
  71863. PoseEnabledController.prototype.getForwardRay = function (length) {
  71864. if (length === void 0) { length = 100; }
  71865. if (!this.mesh) {
  71866. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71867. }
  71868. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71869. var origin = m.getTranslation();
  71870. var forward = new BABYLON.Vector3(0, 0, -1);
  71871. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71872. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71873. return new BABYLON.Ray(origin, direction, length);
  71874. };
  71875. /**
  71876. * Name of the child mesh that can be used to cast a ray from the controller
  71877. */
  71878. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71879. return PoseEnabledController;
  71880. }(BABYLON.Gamepad));
  71881. BABYLON.PoseEnabledController = PoseEnabledController;
  71882. })(BABYLON || (BABYLON = {}));
  71883. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71884. var BABYLON;
  71885. (function (BABYLON) {
  71886. /**
  71887. * Defines the WebVRController object that represents controllers tracked in 3D space
  71888. */
  71889. var WebVRController = /** @class */ (function (_super) {
  71890. __extends(WebVRController, _super);
  71891. /**
  71892. * Creates a new WebVRController from a gamepad
  71893. * @param vrGamepad the gamepad that the WebVRController should be created from
  71894. */
  71895. function WebVRController(vrGamepad) {
  71896. var _this = _super.call(this, vrGamepad) || this;
  71897. // Observables
  71898. /**
  71899. * Fired when the trigger state has changed
  71900. */
  71901. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71902. /**
  71903. * Fired when the main button state has changed
  71904. */
  71905. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71906. /**
  71907. * Fired when the secondary button state has changed
  71908. */
  71909. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71910. /**
  71911. * Fired when the pad state has changed
  71912. */
  71913. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71914. /**
  71915. * Fired when controllers stick values have changed
  71916. */
  71917. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71918. /**
  71919. * X and Y axis corrisponding to the controllers joystick
  71920. */
  71921. _this.pad = { x: 0, y: 0 };
  71922. // avoid GC, store state in a tmp object
  71923. _this._changes = {
  71924. pressChanged: false,
  71925. touchChanged: false,
  71926. valueChanged: false,
  71927. changed: false
  71928. };
  71929. _this._buttons = new Array(vrGamepad.buttons.length);
  71930. _this.hand = vrGamepad.hand;
  71931. return _this;
  71932. }
  71933. /**
  71934. * Fired when a controller button's state has changed
  71935. * @param callback the callback containing the button that was modified
  71936. */
  71937. WebVRController.prototype.onButtonStateChange = function (callback) {
  71938. this._onButtonStateChange = callback;
  71939. };
  71940. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71941. /**
  71942. * The default controller model for the controller
  71943. */
  71944. get: function () {
  71945. return this._defaultModel;
  71946. },
  71947. enumerable: true,
  71948. configurable: true
  71949. });
  71950. /**
  71951. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71952. */
  71953. WebVRController.prototype.update = function () {
  71954. _super.prototype.update.call(this);
  71955. for (var index = 0; index < this._buttons.length; index++) {
  71956. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71957. }
  71958. ;
  71959. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71960. this.pad.x = this.leftStick.x;
  71961. this.pad.y = this.leftStick.y;
  71962. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71963. }
  71964. };
  71965. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71966. if (!newState) {
  71967. newState = {
  71968. pressed: false,
  71969. touched: false,
  71970. value: 0
  71971. };
  71972. }
  71973. if (!currentState) {
  71974. this._buttons[buttonIndex] = {
  71975. pressed: newState.pressed,
  71976. touched: newState.touched,
  71977. value: newState.value
  71978. };
  71979. return;
  71980. }
  71981. this._checkChanges(newState, currentState);
  71982. if (this._changes.changed) {
  71983. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71984. this._handleButtonChange(buttonIndex, newState, this._changes);
  71985. }
  71986. this._buttons[buttonIndex].pressed = newState.pressed;
  71987. this._buttons[buttonIndex].touched = newState.touched;
  71988. // oculus triggers are never 0, thou not touched.
  71989. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71990. };
  71991. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71992. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71993. this._changes.touchChanged = newState.touched !== currentState.touched;
  71994. this._changes.valueChanged = newState.value !== currentState.value;
  71995. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71996. return this._changes;
  71997. };
  71998. /**
  71999. * Disposes of th webVRCOntroller
  72000. */
  72001. WebVRController.prototype.dispose = function () {
  72002. _super.prototype.dispose.call(this);
  72003. this.onTriggerStateChangedObservable.clear();
  72004. this.onMainButtonStateChangedObservable.clear();
  72005. this.onSecondaryButtonStateChangedObservable.clear();
  72006. this.onPadStateChangedObservable.clear();
  72007. this.onPadValuesChangedObservable.clear();
  72008. };
  72009. return WebVRController;
  72010. }(BABYLON.PoseEnabledController));
  72011. BABYLON.WebVRController = WebVRController;
  72012. })(BABYLON || (BABYLON = {}));
  72013. //# sourceMappingURL=babylon.webVRController.js.map
  72014. var BABYLON;
  72015. (function (BABYLON) {
  72016. /**
  72017. * Oculus Touch Controller
  72018. */
  72019. var OculusTouchController = /** @class */ (function (_super) {
  72020. __extends(OculusTouchController, _super);
  72021. /**
  72022. * Creates a new OculusTouchController from a gamepad
  72023. * @param vrGamepad the gamepad that the controller should be created from
  72024. */
  72025. function OculusTouchController(vrGamepad) {
  72026. var _this = _super.call(this, vrGamepad) || this;
  72027. /**
  72028. * Fired when the secondary trigger on this controller is modified
  72029. */
  72030. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72031. /**
  72032. * Fired when the thumb rest on this controller is modified
  72033. */
  72034. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72035. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72036. return _this;
  72037. }
  72038. /**
  72039. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72040. * @param scene scene in which to add meshes
  72041. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72042. */
  72043. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72044. var _this = this;
  72045. var meshName;
  72046. // Hand
  72047. if (this.hand === 'left') {
  72048. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72049. }
  72050. else { // Right is the default if no hand is specified
  72051. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72052. }
  72053. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72054. /*
  72055. Parent Mesh name: oculus_touch_left
  72056. - body
  72057. - trigger
  72058. - thumbstick
  72059. - grip
  72060. - button_y
  72061. - button_x
  72062. - button_enter
  72063. */
  72064. _this._defaultModel = newMeshes[1];
  72065. _this.attachToMesh(_this._defaultModel);
  72066. if (meshLoaded) {
  72067. meshLoaded(_this._defaultModel);
  72068. }
  72069. });
  72070. };
  72071. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72072. /**
  72073. * Fired when the A button on this controller is modified
  72074. */
  72075. get: function () {
  72076. if (this.hand === 'right') {
  72077. return this.onMainButtonStateChangedObservable;
  72078. }
  72079. else {
  72080. throw new Error('No A button on left hand');
  72081. }
  72082. },
  72083. enumerable: true,
  72084. configurable: true
  72085. });
  72086. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72087. /**
  72088. * Fired when the B button on this controller is modified
  72089. */
  72090. get: function () {
  72091. if (this.hand === 'right') {
  72092. return this.onSecondaryButtonStateChangedObservable;
  72093. }
  72094. else {
  72095. throw new Error('No B button on left hand');
  72096. }
  72097. },
  72098. enumerable: true,
  72099. configurable: true
  72100. });
  72101. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72102. /**
  72103. * Fired when the X button on this controller is modified
  72104. */
  72105. get: function () {
  72106. if (this.hand === 'left') {
  72107. return this.onMainButtonStateChangedObservable;
  72108. }
  72109. else {
  72110. throw new Error('No X button on right hand');
  72111. }
  72112. },
  72113. enumerable: true,
  72114. configurable: true
  72115. });
  72116. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72117. /**
  72118. * Fired when the Y button on this controller is modified
  72119. */
  72120. get: function () {
  72121. if (this.hand === 'left') {
  72122. return this.onSecondaryButtonStateChangedObservable;
  72123. }
  72124. else {
  72125. throw new Error('No Y button on right hand');
  72126. }
  72127. },
  72128. enumerable: true,
  72129. configurable: true
  72130. });
  72131. /**
  72132. * Called once for each button that changed state since the last frame
  72133. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72134. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72135. * 2) secondary trigger (same)
  72136. * 3) A (right) X (left), touch, pressed = value
  72137. * 4) B / Y
  72138. * 5) thumb rest
  72139. * @param buttonIdx Which button index changed
  72140. * @param state New state of the button
  72141. * @param changes Which properties on the state changed since last frame
  72142. */
  72143. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72144. var notifyObject = state; //{ state: state, changes: changes };
  72145. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72146. switch (buttonIdx) {
  72147. case 0:
  72148. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72149. return;
  72150. case 1: // index trigger
  72151. if (this._defaultModel) {
  72152. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72153. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72154. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72155. }
  72156. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72157. return;
  72158. case 2: // secondary trigger
  72159. if (this._defaultModel) {
  72160. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72161. }
  72162. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72163. return;
  72164. case 3:
  72165. if (this._defaultModel) {
  72166. if (notifyObject.pressed) {
  72167. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72168. }
  72169. else {
  72170. (this._defaultModel.getChildren()[1]).position.y = 0;
  72171. }
  72172. }
  72173. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72174. return;
  72175. case 4:
  72176. if (this._defaultModel) {
  72177. if (notifyObject.pressed) {
  72178. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72179. }
  72180. else {
  72181. (this._defaultModel.getChildren()[2]).position.y = 0;
  72182. }
  72183. }
  72184. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72185. return;
  72186. case 5:
  72187. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72188. return;
  72189. }
  72190. };
  72191. /**
  72192. * Base Url for the controller model.
  72193. */
  72194. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72195. /**
  72196. * File name for the left controller model.
  72197. */
  72198. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72199. /**
  72200. * File name for the right controller model.
  72201. */
  72202. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72203. return OculusTouchController;
  72204. }(BABYLON.WebVRController));
  72205. BABYLON.OculusTouchController = OculusTouchController;
  72206. })(BABYLON || (BABYLON = {}));
  72207. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72208. var BABYLON;
  72209. (function (BABYLON) {
  72210. /**
  72211. * Vive Controller
  72212. */
  72213. var ViveController = /** @class */ (function (_super) {
  72214. __extends(ViveController, _super);
  72215. /**
  72216. * Creates a new ViveController from a gamepad
  72217. * @param vrGamepad the gamepad that the controller should be created from
  72218. */
  72219. function ViveController(vrGamepad) {
  72220. var _this = _super.call(this, vrGamepad) || this;
  72221. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72222. _this._invertLeftStickY = true;
  72223. return _this;
  72224. }
  72225. /**
  72226. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72227. * @param scene scene in which to add meshes
  72228. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72229. */
  72230. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72231. var _this = this;
  72232. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72233. /*
  72234. Parent Mesh name: ViveWand
  72235. - body
  72236. - r_gripper
  72237. - l_gripper
  72238. - menu_button
  72239. - system_button
  72240. - trackpad
  72241. - trigger
  72242. - LED
  72243. */
  72244. _this._defaultModel = newMeshes[1];
  72245. _this.attachToMesh(_this._defaultModel);
  72246. if (meshLoaded) {
  72247. meshLoaded(_this._defaultModel);
  72248. }
  72249. });
  72250. };
  72251. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72252. /**
  72253. * Fired when the left button on this controller is modified
  72254. */
  72255. get: function () {
  72256. return this.onMainButtonStateChangedObservable;
  72257. },
  72258. enumerable: true,
  72259. configurable: true
  72260. });
  72261. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72262. /**
  72263. * Fired when the right button on this controller is modified
  72264. */
  72265. get: function () {
  72266. return this.onMainButtonStateChangedObservable;
  72267. },
  72268. enumerable: true,
  72269. configurable: true
  72270. });
  72271. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72272. /**
  72273. * Fired when the menu button on this controller is modified
  72274. */
  72275. get: function () {
  72276. return this.onSecondaryButtonStateChangedObservable;
  72277. },
  72278. enumerable: true,
  72279. configurable: true
  72280. });
  72281. /**
  72282. * Called once for each button that changed state since the last frame
  72283. * Vive mapping:
  72284. * 0: touchpad
  72285. * 1: trigger
  72286. * 2: left AND right buttons
  72287. * 3: menu button
  72288. * @param buttonIdx Which button index changed
  72289. * @param state New state of the button
  72290. * @param changes Which properties on the state changed since last frame
  72291. */
  72292. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72293. var notifyObject = state; //{ state: state, changes: changes };
  72294. switch (buttonIdx) {
  72295. case 0:
  72296. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72297. return;
  72298. case 1: // index trigger
  72299. if (this._defaultModel) {
  72300. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72301. }
  72302. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72303. return;
  72304. case 2: // left AND right button
  72305. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72306. return;
  72307. case 3:
  72308. if (this._defaultModel) {
  72309. if (notifyObject.pressed) {
  72310. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72311. }
  72312. else {
  72313. (this._defaultModel.getChildren()[2]).position.y = 0;
  72314. }
  72315. }
  72316. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72317. return;
  72318. }
  72319. };
  72320. /**
  72321. * Base Url for the controller model.
  72322. */
  72323. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72324. /**
  72325. * File name for the controller model.
  72326. */
  72327. ViveController.MODEL_FILENAME = 'wand.babylon';
  72328. return ViveController;
  72329. }(BABYLON.WebVRController));
  72330. BABYLON.ViveController = ViveController;
  72331. })(BABYLON || (BABYLON = {}));
  72332. //# sourceMappingURL=babylon.viveController.js.map
  72333. var BABYLON;
  72334. (function (BABYLON) {
  72335. /**
  72336. * Generic Controller
  72337. */
  72338. var GenericController = /** @class */ (function (_super) {
  72339. __extends(GenericController, _super);
  72340. /**
  72341. * Creates a new GenericController from a gamepad
  72342. * @param vrGamepad the gamepad that the controller should be created from
  72343. */
  72344. function GenericController(vrGamepad) {
  72345. return _super.call(this, vrGamepad) || this;
  72346. }
  72347. /**
  72348. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72349. * @param scene scene in which to add meshes
  72350. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72351. */
  72352. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72353. var _this = this;
  72354. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72355. _this._defaultModel = newMeshes[1];
  72356. _this.attachToMesh(_this._defaultModel);
  72357. if (meshLoaded) {
  72358. meshLoaded(_this._defaultModel);
  72359. }
  72360. });
  72361. };
  72362. /**
  72363. * Called once for each button that changed state since the last frame
  72364. * @param buttonIdx Which button index changed
  72365. * @param state New state of the button
  72366. * @param changes Which properties on the state changed since last frame
  72367. */
  72368. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72369. console.log("Button id: " + buttonIdx + "state: ");
  72370. console.dir(state);
  72371. };
  72372. /**
  72373. * Base Url for the controller model.
  72374. */
  72375. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72376. /**
  72377. * File name for the controller model.
  72378. */
  72379. GenericController.MODEL_FILENAME = 'generic.babylon';
  72380. return GenericController;
  72381. }(BABYLON.WebVRController));
  72382. BABYLON.GenericController = GenericController;
  72383. })(BABYLON || (BABYLON = {}));
  72384. //# sourceMappingURL=babylon.genericController.js.map
  72385. var BABYLON;
  72386. (function (BABYLON) {
  72387. /**
  72388. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72389. */
  72390. var LoadedMeshInfo = /** @class */ (function () {
  72391. function LoadedMeshInfo() {
  72392. /**
  72393. * Map of the button meshes contained in the controller
  72394. */
  72395. this.buttonMeshes = {};
  72396. /**
  72397. * Map of the axis meshes contained in the controller
  72398. */
  72399. this.axisMeshes = {};
  72400. }
  72401. return LoadedMeshInfo;
  72402. }());
  72403. /**
  72404. * Defines the WindowsMotionController object that the state of the windows motion controller
  72405. */
  72406. var WindowsMotionController = /** @class */ (function (_super) {
  72407. __extends(WindowsMotionController, _super);
  72408. /**
  72409. * Creates a new WindowsMotionController from a gamepad
  72410. * @param vrGamepad the gamepad that the controller should be created from
  72411. */
  72412. function WindowsMotionController(vrGamepad) {
  72413. var _this = _super.call(this, vrGamepad) || this;
  72414. _this._mapping = {
  72415. // Semantic button names
  72416. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72417. // A mapping of the button name to glTF model node name
  72418. // that should be transformed by button value.
  72419. buttonMeshNames: {
  72420. 'trigger': 'SELECT',
  72421. 'menu': 'MENU',
  72422. 'grip': 'GRASP',
  72423. 'thumbstick': 'THUMBSTICK_PRESS',
  72424. 'trackpad': 'TOUCHPAD_PRESS'
  72425. },
  72426. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72427. buttonObservableNames: {
  72428. 'trigger': 'onTriggerStateChangedObservable',
  72429. 'menu': 'onSecondaryButtonStateChangedObservable',
  72430. 'grip': 'onMainButtonStateChangedObservable',
  72431. 'thumbstick': 'onPadStateChangedObservable',
  72432. 'trackpad': 'onTrackpadChangedObservable'
  72433. },
  72434. // A mapping of the axis name to glTF model node name
  72435. // that should be transformed by axis value.
  72436. // This array mirrors the browserGamepad.axes array, such that
  72437. // the mesh corresponding to axis 0 is in this array index 0.
  72438. axisMeshNames: [
  72439. 'THUMBSTICK_X',
  72440. 'THUMBSTICK_Y',
  72441. 'TOUCHPAD_TOUCH_X',
  72442. 'TOUCHPAD_TOUCH_Y'
  72443. ],
  72444. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72445. };
  72446. /**
  72447. * Fired when the trackpad on this controller is clicked
  72448. */
  72449. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72450. /**
  72451. * Fired when the trackpad on this controller is modified
  72452. */
  72453. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72454. /**
  72455. * The current x and y values of this controller's trackpad
  72456. */
  72457. _this.trackpad = { x: 0, y: 0 };
  72458. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72459. _this._loadedMeshInfo = null;
  72460. return _this;
  72461. }
  72462. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72463. /**
  72464. * Fired when the trigger on this controller is modified
  72465. */
  72466. get: function () {
  72467. return this.onTriggerStateChangedObservable;
  72468. },
  72469. enumerable: true,
  72470. configurable: true
  72471. });
  72472. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72473. /**
  72474. * Fired when the menu button on this controller is modified
  72475. */
  72476. get: function () {
  72477. return this.onSecondaryButtonStateChangedObservable;
  72478. },
  72479. enumerable: true,
  72480. configurable: true
  72481. });
  72482. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72483. /**
  72484. * Fired when the grip button on this controller is modified
  72485. */
  72486. get: function () {
  72487. return this.onMainButtonStateChangedObservable;
  72488. },
  72489. enumerable: true,
  72490. configurable: true
  72491. });
  72492. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72493. /**
  72494. * Fired when the thumbstick button on this controller is modified
  72495. */
  72496. get: function () {
  72497. return this.onPadStateChangedObservable;
  72498. },
  72499. enumerable: true,
  72500. configurable: true
  72501. });
  72502. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72503. /**
  72504. * Fired when the touchpad button on this controller is modified
  72505. */
  72506. get: function () {
  72507. return this.onTrackpadChangedObservable;
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72513. /**
  72514. * Fired when the touchpad values on this controller are modified
  72515. */
  72516. get: function () {
  72517. return this.onTrackpadValuesChangedObservable;
  72518. },
  72519. enumerable: true,
  72520. configurable: true
  72521. });
  72522. /**
  72523. * Called once per frame by the engine.
  72524. */
  72525. WindowsMotionController.prototype.update = function () {
  72526. _super.prototype.update.call(this);
  72527. if (this.browserGamepad.axes) {
  72528. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72529. this.trackpad.x = this.browserGamepad["axes"][2];
  72530. this.trackpad.y = this.browserGamepad["axes"][3];
  72531. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72532. }
  72533. // Only need to animate axes if there is a loaded mesh
  72534. if (this._loadedMeshInfo) {
  72535. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72536. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72537. }
  72538. }
  72539. }
  72540. };
  72541. /**
  72542. * Called once for each button that changed state since the last frame
  72543. * @param buttonIdx Which button index changed
  72544. * @param state New state of the button
  72545. * @param changes Which properties on the state changed since last frame
  72546. */
  72547. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72548. var buttonName = this._mapping.buttons[buttonIdx];
  72549. if (!buttonName) {
  72550. return;
  72551. }
  72552. // Only emit events for buttons that we know how to map from index to name
  72553. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72554. if (observable) {
  72555. observable.notifyObservers(state);
  72556. }
  72557. this._lerpButtonTransform(buttonName, state.value);
  72558. };
  72559. /**
  72560. * Moves the buttons on the controller mesh based on their current state
  72561. * @param buttonName the name of the button to move
  72562. * @param buttonValue the value of the button which determines the buttons new position
  72563. */
  72564. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72565. // If there is no loaded mesh, there is nothing to transform.
  72566. if (!this._loadedMeshInfo) {
  72567. return;
  72568. }
  72569. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72570. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72571. return;
  72572. }
  72573. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72574. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72575. };
  72576. /**
  72577. * Moves the axis on the controller mesh based on its current state
  72578. * @param axis the index of the axis
  72579. * @param axisValue the value of the axis which determines the meshes new position
  72580. * @hidden
  72581. */
  72582. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72583. if (!this._loadedMeshInfo) {
  72584. return;
  72585. }
  72586. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72587. if (!meshInfo) {
  72588. return;
  72589. }
  72590. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72591. return;
  72592. }
  72593. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72594. var lerpValue = axisValue * 0.5 + 0.5;
  72595. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72596. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72597. };
  72598. /**
  72599. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72600. * @param scene scene in which to add meshes
  72601. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72602. */
  72603. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72604. var _this = this;
  72605. if (forceDefault === void 0) { forceDefault = false; }
  72606. var path;
  72607. var filename;
  72608. // Checking if GLB loader is present
  72609. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72610. // Determine the device specific folder based on the ID suffix
  72611. var device = 'default';
  72612. if (this.id && !forceDefault) {
  72613. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72614. device = ((match && match[0]) || device);
  72615. }
  72616. // Hand
  72617. if (this.hand === 'left') {
  72618. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72619. }
  72620. else { // Right is the default if no hand is specified
  72621. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72622. }
  72623. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72624. }
  72625. else {
  72626. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72627. path = BABYLON.GenericController.MODEL_BASE_URL;
  72628. filename = BABYLON.GenericController.MODEL_FILENAME;
  72629. }
  72630. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72631. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72632. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72633. if (!_this._loadedMeshInfo) {
  72634. return;
  72635. }
  72636. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72637. _this.attachToMesh(_this._defaultModel);
  72638. if (meshLoaded) {
  72639. meshLoaded(_this._defaultModel);
  72640. }
  72641. }, null, function (scene, message) {
  72642. BABYLON.Tools.Log(message);
  72643. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72644. if (!forceDefault) {
  72645. _this.initControllerMesh(scene, meshLoaded, true);
  72646. }
  72647. });
  72648. };
  72649. /**
  72650. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72651. * can be transformed by button presses and axes values, based on this._mapping.
  72652. *
  72653. * @param scene scene in which the meshes exist
  72654. * @param meshes list of meshes that make up the controller model to process
  72655. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72656. */
  72657. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72658. var loadedMeshInfo = null;
  72659. // Create a new mesh to contain the glTF hierarchy
  72660. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72661. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72662. var childMesh = null;
  72663. for (var i = 0; i < meshes.length; i++) {
  72664. var mesh = meshes[i];
  72665. if (!mesh.parent) {
  72666. // Exclude controller meshes from picking results
  72667. mesh.isPickable = false;
  72668. // Handle root node, attach to the new parentMesh
  72669. childMesh = mesh;
  72670. break;
  72671. }
  72672. }
  72673. if (childMesh) {
  72674. childMesh.setParent(parentMesh);
  72675. // Create our mesh info. Note that this method will always return non-null.
  72676. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72677. }
  72678. else {
  72679. BABYLON.Tools.Warn('Could not find root node in model file.');
  72680. }
  72681. return loadedMeshInfo;
  72682. };
  72683. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72684. var loadedMeshInfo = new LoadedMeshInfo();
  72685. var i;
  72686. loadedMeshInfo.rootNode = rootNode;
  72687. // Reset the caches
  72688. loadedMeshInfo.buttonMeshes = {};
  72689. loadedMeshInfo.axisMeshes = {};
  72690. // Button Meshes
  72691. for (i = 0; i < this._mapping.buttons.length; i++) {
  72692. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72693. if (!buttonMeshName) {
  72694. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72695. continue;
  72696. }
  72697. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72698. if (!buttonMesh) {
  72699. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72700. continue;
  72701. }
  72702. var buttonMeshInfo = {
  72703. index: i,
  72704. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72705. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72706. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72707. };
  72708. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72709. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72710. }
  72711. else {
  72712. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72713. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72714. '(VALUE: ' + !!buttonMeshInfo.value +
  72715. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72716. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72717. ')');
  72718. }
  72719. }
  72720. // Axis Meshes
  72721. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72722. var axisMeshName = this._mapping.axisMeshNames[i];
  72723. if (!axisMeshName) {
  72724. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72725. continue;
  72726. }
  72727. var axisMesh = getChildByName(rootNode, axisMeshName);
  72728. if (!axisMesh) {
  72729. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72730. continue;
  72731. }
  72732. var axisMeshInfo = {
  72733. index: i,
  72734. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72735. min: getImmediateChildByName(axisMesh, 'MIN'),
  72736. max: getImmediateChildByName(axisMesh, 'MAX')
  72737. };
  72738. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72739. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72740. }
  72741. else {
  72742. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72743. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72744. '(VALUE: ' + !!axisMeshInfo.value +
  72745. ', MIN: ' + !!axisMeshInfo.min +
  72746. ', MAX:' + !!axisMeshInfo.max +
  72747. ')');
  72748. }
  72749. }
  72750. // Pointing Ray
  72751. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72752. if (!loadedMeshInfo.pointingPoseNode) {
  72753. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72754. }
  72755. return loadedMeshInfo;
  72756. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72757. function getChildByName(node, name) {
  72758. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72759. }
  72760. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72761. function getImmediateChildByName(node, name) {
  72762. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72763. }
  72764. };
  72765. /**
  72766. * Gets the ray of the controller in the direction the controller is pointing
  72767. * @param length the length the resulting ray should be
  72768. * @returns a ray in the direction the controller is pointing
  72769. */
  72770. WindowsMotionController.prototype.getForwardRay = function (length) {
  72771. if (length === void 0) { length = 100; }
  72772. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72773. return _super.prototype.getForwardRay.call(this, length);
  72774. }
  72775. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72776. var origin = m.getTranslation();
  72777. var forward = new BABYLON.Vector3(0, 0, -1);
  72778. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72779. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72780. return new BABYLON.Ray(origin, direction, length);
  72781. };
  72782. /**
  72783. * Disposes of the controller
  72784. */
  72785. WindowsMotionController.prototype.dispose = function () {
  72786. _super.prototype.dispose.call(this);
  72787. this.onTrackpadChangedObservable.clear();
  72788. };
  72789. /**
  72790. * The base url used to load the left and right controller models
  72791. */
  72792. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72793. /**
  72794. * The name of the left controller model file
  72795. */
  72796. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72797. /**
  72798. * The name of the right controller model file
  72799. */
  72800. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72801. /**
  72802. * The controller name prefix for this controller type
  72803. */
  72804. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72805. /**
  72806. * The controller id pattern for this controller type
  72807. */
  72808. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72809. return WindowsMotionController;
  72810. }(BABYLON.WebVRController));
  72811. BABYLON.WindowsMotionController = WindowsMotionController;
  72812. })(BABYLON || (BABYLON = {}));
  72813. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72814. var BABYLON;
  72815. (function (BABYLON) {
  72816. /**
  72817. * Gear VR Controller
  72818. */
  72819. var GearVRController = /** @class */ (function (_super) {
  72820. __extends(GearVRController, _super);
  72821. /**
  72822. * Creates a new GearVRController from a gamepad
  72823. * @param vrGamepad the gamepad that the controller should be created from
  72824. */
  72825. function GearVRController(vrGamepad) {
  72826. var _this = _super.call(this, vrGamepad) || this;
  72827. _this._buttonIndexToObservableNameMap = [
  72828. 'onTrackpadChangedObservable',
  72829. 'onTriggerStateChangedObservable' // Trigger
  72830. ];
  72831. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72832. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72833. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72834. return _this;
  72835. }
  72836. /**
  72837. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72838. * @param scene scene in which to add meshes
  72839. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72840. */
  72841. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72842. var _this = this;
  72843. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72844. _this._defaultModel = newMeshes[1];
  72845. _this.attachToMesh(_this._defaultModel);
  72846. if (meshLoaded) {
  72847. meshLoaded(_this._defaultModel);
  72848. }
  72849. });
  72850. };
  72851. /**
  72852. * Called once for each button that changed state since the last frame
  72853. * @param buttonIdx Which button index changed
  72854. * @param state New state of the button
  72855. * @param changes Which properties on the state changed since last frame
  72856. */
  72857. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72858. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72859. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72860. // Only emit events for buttons that we know how to map from index to observable
  72861. var observable = this[observableName];
  72862. if (observable) {
  72863. observable.notifyObservers(state);
  72864. }
  72865. }
  72866. };
  72867. /**
  72868. * Base Url for the controller model.
  72869. */
  72870. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72871. /**
  72872. * File name for the controller model.
  72873. */
  72874. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72875. /**
  72876. * Gamepad Id prefix used to identify this controller.
  72877. */
  72878. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72879. return GearVRController;
  72880. }(BABYLON.WebVRController));
  72881. BABYLON.GearVRController = GearVRController;
  72882. })(BABYLON || (BABYLON = {}));
  72883. //# sourceMappingURL=babylon.gearVRController.js.map
  72884. var BABYLON;
  72885. (function (BABYLON) {
  72886. /**
  72887. * Google Daydream controller
  72888. */
  72889. var DaydreamController = /** @class */ (function (_super) {
  72890. __extends(DaydreamController, _super);
  72891. /**
  72892. * Creates a new DaydreamController from a gamepad
  72893. * @param vrGamepad the gamepad that the controller should be created from
  72894. */
  72895. function DaydreamController(vrGamepad) {
  72896. var _this = _super.call(this, vrGamepad) || this;
  72897. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72898. return _this;
  72899. }
  72900. /**
  72901. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72902. * @param scene scene in which to add meshes
  72903. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72904. */
  72905. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72906. var _this = this;
  72907. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72908. _this._defaultModel = newMeshes[1];
  72909. _this.attachToMesh(_this._defaultModel);
  72910. if (meshLoaded) {
  72911. meshLoaded(_this._defaultModel);
  72912. }
  72913. });
  72914. };
  72915. /**
  72916. * Called once for each button that changed state since the last frame
  72917. * @param buttonIdx Which button index changed
  72918. * @param state New state of the button
  72919. * @param changes Which properties on the state changed since last frame
  72920. */
  72921. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72922. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72923. if (buttonIdx === 0) {
  72924. var observable = this.onTriggerStateChangedObservable;
  72925. if (observable) {
  72926. observable.notifyObservers(state);
  72927. }
  72928. }
  72929. else {
  72930. // If the app or home buttons are ever made available
  72931. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72932. }
  72933. };
  72934. /**
  72935. * Base Url for the controller model.
  72936. */
  72937. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72938. /**
  72939. * File name for the controller model.
  72940. */
  72941. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72942. /**
  72943. * Gamepad Id prefix used to identify Daydream Controller.
  72944. */
  72945. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72946. return DaydreamController;
  72947. }(BABYLON.WebVRController));
  72948. BABYLON.DaydreamController = DaydreamController;
  72949. })(BABYLON || (BABYLON = {}));
  72950. //# sourceMappingURL=babylon.daydreamController.js.map
  72951. var BABYLON;
  72952. (function (BABYLON) {
  72953. var FollowCamera = /** @class */ (function (_super) {
  72954. __extends(FollowCamera, _super);
  72955. function FollowCamera(name, position, scene, lockedTarget) {
  72956. if (lockedTarget === void 0) { lockedTarget = null; }
  72957. var _this = _super.call(this, name, position, scene) || this;
  72958. _this.radius = 12;
  72959. _this.rotationOffset = 0;
  72960. _this.heightOffset = 4;
  72961. _this.cameraAcceleration = 0.05;
  72962. _this.maxCameraSpeed = 20;
  72963. _this.lockedTarget = lockedTarget;
  72964. return _this;
  72965. }
  72966. FollowCamera.prototype.getRadians = function (degrees) {
  72967. return degrees * Math.PI / 180;
  72968. };
  72969. FollowCamera.prototype.follow = function (cameraTarget) {
  72970. if (!cameraTarget)
  72971. return;
  72972. var yRotation;
  72973. if (cameraTarget.rotationQuaternion) {
  72974. var rotMatrix = new BABYLON.Matrix();
  72975. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72976. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72977. }
  72978. else {
  72979. yRotation = cameraTarget.rotation.y;
  72980. }
  72981. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72982. var targetPosition = cameraTarget.getAbsolutePosition();
  72983. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72984. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72985. var dx = targetX - this.position.x;
  72986. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72987. var dz = (targetZ) - this.position.z;
  72988. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72989. var vy = dy * this.cameraAcceleration;
  72990. var vz = dz * this.cameraAcceleration * 2;
  72991. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72992. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72993. }
  72994. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72995. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72996. }
  72997. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72998. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72999. }
  73000. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73001. this.setTarget(targetPosition);
  73002. };
  73003. FollowCamera.prototype._checkInputs = function () {
  73004. _super.prototype._checkInputs.call(this);
  73005. if (this.lockedTarget) {
  73006. this.follow(this.lockedTarget);
  73007. }
  73008. };
  73009. FollowCamera.prototype.getClassName = function () {
  73010. return "FollowCamera";
  73011. };
  73012. __decorate([
  73013. BABYLON.serialize()
  73014. ], FollowCamera.prototype, "radius", void 0);
  73015. __decorate([
  73016. BABYLON.serialize()
  73017. ], FollowCamera.prototype, "rotationOffset", void 0);
  73018. __decorate([
  73019. BABYLON.serialize()
  73020. ], FollowCamera.prototype, "heightOffset", void 0);
  73021. __decorate([
  73022. BABYLON.serialize()
  73023. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73024. __decorate([
  73025. BABYLON.serialize()
  73026. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73027. __decorate([
  73028. BABYLON.serializeAsMeshReference("lockedTargetId")
  73029. ], FollowCamera.prototype, "lockedTarget", void 0);
  73030. return FollowCamera;
  73031. }(BABYLON.TargetCamera));
  73032. BABYLON.FollowCamera = FollowCamera;
  73033. var ArcFollowCamera = /** @class */ (function (_super) {
  73034. __extends(ArcFollowCamera, _super);
  73035. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73036. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73037. _this.alpha = alpha;
  73038. _this.beta = beta;
  73039. _this.radius = radius;
  73040. _this.target = target;
  73041. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73042. _this.follow();
  73043. return _this;
  73044. }
  73045. ArcFollowCamera.prototype.follow = function () {
  73046. if (!this.target) {
  73047. return;
  73048. }
  73049. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73050. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73051. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73052. var targetPosition = this.target.getAbsolutePosition();
  73053. this.position = targetPosition.add(this._cartesianCoordinates);
  73054. this.setTarget(targetPosition);
  73055. };
  73056. ArcFollowCamera.prototype._checkInputs = function () {
  73057. _super.prototype._checkInputs.call(this);
  73058. this.follow();
  73059. };
  73060. ArcFollowCamera.prototype.getClassName = function () {
  73061. return "ArcFollowCamera";
  73062. };
  73063. return ArcFollowCamera;
  73064. }(BABYLON.TargetCamera));
  73065. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73066. })(BABYLON || (BABYLON = {}));
  73067. //# sourceMappingURL=babylon.followCamera.js.map
  73068. var BABYLON;
  73069. (function (BABYLON) {
  73070. // We're mainly based on the logic defined into the FreeCamera code
  73071. var UniversalCamera = /** @class */ (function (_super) {
  73072. __extends(UniversalCamera, _super);
  73073. //-- end properties for backward compatibility for inputs
  73074. function UniversalCamera(name, position, scene) {
  73075. var _this = _super.call(this, name, position, scene) || this;
  73076. _this.inputs.addGamepad();
  73077. return _this;
  73078. }
  73079. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73080. //-- Begin properties for backward compatibility for inputs
  73081. get: function () {
  73082. var gamepad = this.inputs.attached["gamepad"];
  73083. if (gamepad)
  73084. return gamepad.gamepadAngularSensibility;
  73085. return 0;
  73086. },
  73087. set: function (value) {
  73088. var gamepad = this.inputs.attached["gamepad"];
  73089. if (gamepad)
  73090. gamepad.gamepadAngularSensibility = value;
  73091. },
  73092. enumerable: true,
  73093. configurable: true
  73094. });
  73095. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73096. get: function () {
  73097. var gamepad = this.inputs.attached["gamepad"];
  73098. if (gamepad)
  73099. return gamepad.gamepadMoveSensibility;
  73100. return 0;
  73101. },
  73102. set: function (value) {
  73103. var gamepad = this.inputs.attached["gamepad"];
  73104. if (gamepad)
  73105. gamepad.gamepadMoveSensibility = value;
  73106. },
  73107. enumerable: true,
  73108. configurable: true
  73109. });
  73110. UniversalCamera.prototype.getClassName = function () {
  73111. return "UniversalCamera";
  73112. };
  73113. return UniversalCamera;
  73114. }(BABYLON.TouchCamera));
  73115. BABYLON.UniversalCamera = UniversalCamera;
  73116. })(BABYLON || (BABYLON = {}));
  73117. //# sourceMappingURL=babylon.universalCamera.js.map
  73118. var BABYLON;
  73119. (function (BABYLON) {
  73120. // We're mainly based on the logic defined into the FreeCamera code
  73121. var GamepadCamera = /** @class */ (function (_super) {
  73122. __extends(GamepadCamera, _super);
  73123. //-- end properties for backward compatibility for inputs
  73124. function GamepadCamera(name, position, scene) {
  73125. return _super.call(this, name, position, scene) || this;
  73126. }
  73127. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73128. //-- Begin properties for backward compatibility for inputs
  73129. get: function () {
  73130. var gamepad = this.inputs.attached["gamepad"];
  73131. if (gamepad)
  73132. return gamepad.gamepadAngularSensibility;
  73133. return 0;
  73134. },
  73135. set: function (value) {
  73136. var gamepad = this.inputs.attached["gamepad"];
  73137. if (gamepad)
  73138. gamepad.gamepadAngularSensibility = value;
  73139. },
  73140. enumerable: true,
  73141. configurable: true
  73142. });
  73143. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73144. get: function () {
  73145. var gamepad = this.inputs.attached["gamepad"];
  73146. if (gamepad)
  73147. return gamepad.gamepadMoveSensibility;
  73148. return 0;
  73149. },
  73150. set: function (value) {
  73151. var gamepad = this.inputs.attached["gamepad"];
  73152. if (gamepad)
  73153. gamepad.gamepadMoveSensibility = value;
  73154. },
  73155. enumerable: true,
  73156. configurable: true
  73157. });
  73158. GamepadCamera.prototype.getClassName = function () {
  73159. return "GamepadCamera";
  73160. };
  73161. return GamepadCamera;
  73162. }(BABYLON.UniversalCamera));
  73163. BABYLON.GamepadCamera = GamepadCamera;
  73164. })(BABYLON || (BABYLON = {}));
  73165. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73166. var BABYLON;
  73167. (function (BABYLON) {
  73168. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73169. function PostProcessRenderPipelineManager() {
  73170. this._renderPipelines = {};
  73171. }
  73172. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73173. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73174. };
  73175. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73176. if (unique === void 0) { unique = false; }
  73177. var renderPipeline = this._renderPipelines[renderPipelineName];
  73178. if (!renderPipeline) {
  73179. return;
  73180. }
  73181. renderPipeline._attachCameras(cameras, unique);
  73182. };
  73183. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73184. var renderPipeline = this._renderPipelines[renderPipelineName];
  73185. if (!renderPipeline) {
  73186. return;
  73187. }
  73188. renderPipeline._detachCameras(cameras);
  73189. };
  73190. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73191. var renderPipeline = this._renderPipelines[renderPipelineName];
  73192. if (!renderPipeline) {
  73193. return;
  73194. }
  73195. renderPipeline._enableEffect(renderEffectName, cameras);
  73196. };
  73197. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73198. var renderPipeline = this._renderPipelines[renderPipelineName];
  73199. if (!renderPipeline) {
  73200. return;
  73201. }
  73202. renderPipeline._disableEffect(renderEffectName, cameras);
  73203. };
  73204. PostProcessRenderPipelineManager.prototype.update = function () {
  73205. for (var renderPipelineName in this._renderPipelines) {
  73206. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73207. var pipeline = this._renderPipelines[renderPipelineName];
  73208. if (!pipeline.isSupported) {
  73209. pipeline.dispose();
  73210. delete this._renderPipelines[renderPipelineName];
  73211. }
  73212. else {
  73213. pipeline._update();
  73214. }
  73215. }
  73216. }
  73217. };
  73218. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73219. for (var renderPipelineName in this._renderPipelines) {
  73220. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73221. var pipeline = this._renderPipelines[renderPipelineName];
  73222. pipeline._rebuild();
  73223. }
  73224. }
  73225. };
  73226. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73227. for (var renderPipelineName in this._renderPipelines) {
  73228. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73229. var pipeline = this._renderPipelines[renderPipelineName];
  73230. pipeline.dispose();
  73231. }
  73232. }
  73233. };
  73234. return PostProcessRenderPipelineManager;
  73235. }());
  73236. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73237. })(BABYLON || (BABYLON = {}));
  73238. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73239. var BABYLON;
  73240. (function (BABYLON) {
  73241. /**
  73242. * This represents a set of one or more post processes in Babylon.
  73243. * A post process can be used to apply a shader to a texture after it is rendered.
  73244. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73245. */
  73246. var PostProcessRenderEffect = /** @class */ (function () {
  73247. /**
  73248. * Instantiates a post process render effect.
  73249. * A post process can be used to apply a shader to a texture after it is rendered.
  73250. * @param engine The engine the effect is tied to
  73251. * @param name The name of the effect
  73252. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73253. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73254. */
  73255. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73256. this._name = name;
  73257. this._singleInstance = singleInstance || true;
  73258. this._getPostProcesses = getPostProcesses;
  73259. this._cameras = {};
  73260. this._indicesForCamera = {};
  73261. this._postProcesses = {};
  73262. }
  73263. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73264. /**
  73265. * Checks if all the post processes in the effect are supported.
  73266. */
  73267. get: function () {
  73268. for (var index in this._postProcesses) {
  73269. if (this._postProcesses.hasOwnProperty(index)) {
  73270. var pps = this._postProcesses[index];
  73271. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73272. if (!pps[ppIndex].isSupported) {
  73273. return false;
  73274. }
  73275. }
  73276. }
  73277. }
  73278. return true;
  73279. },
  73280. enumerable: true,
  73281. configurable: true
  73282. });
  73283. /**
  73284. * Updates the current state of the effect
  73285. */
  73286. PostProcessRenderEffect.prototype._update = function () {
  73287. };
  73288. /**
  73289. * Attaches the effect on cameras
  73290. * @param cameras The camera to attach to.
  73291. */
  73292. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73293. var _this = this;
  73294. var cameraKey;
  73295. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73296. if (!cams) {
  73297. return;
  73298. }
  73299. for (var i = 0; i < cams.length; i++) {
  73300. var camera = cams[i];
  73301. var cameraName = camera.name;
  73302. if (this._singleInstance) {
  73303. cameraKey = 0;
  73304. }
  73305. else {
  73306. cameraKey = cameraName;
  73307. }
  73308. if (!this._postProcesses[cameraKey]) {
  73309. var postProcess = this._getPostProcesses();
  73310. if (postProcess) {
  73311. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73312. }
  73313. }
  73314. if (!this._indicesForCamera[cameraName]) {
  73315. this._indicesForCamera[cameraName] = [];
  73316. }
  73317. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73318. var index = camera.attachPostProcess(postProcess);
  73319. _this._indicesForCamera[cameraName].push(index);
  73320. });
  73321. if (!this._cameras[cameraName]) {
  73322. this._cameras[cameraName] = camera;
  73323. }
  73324. }
  73325. };
  73326. /**
  73327. * Detatches the effect on cameras
  73328. * @param cameras The camera to detatch from.
  73329. */
  73330. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73331. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73332. if (!cams) {
  73333. return;
  73334. }
  73335. for (var i = 0; i < cams.length; i++) {
  73336. var camera = cams[i];
  73337. var cameraName = camera.name;
  73338. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73339. camera.detachPostProcess(postProcess);
  73340. });
  73341. if (this._cameras[cameraName]) {
  73342. //this._indicesForCamera.splice(index, 1);
  73343. this._cameras[cameraName] = null;
  73344. }
  73345. }
  73346. };
  73347. /**
  73348. * Enables the effect on given cameras
  73349. * @param cameras The camera to enable.
  73350. */
  73351. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73352. var _this = this;
  73353. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73354. if (!cams) {
  73355. return;
  73356. }
  73357. for (var i = 0; i < cams.length; i++) {
  73358. var camera = cams[i];
  73359. var cameraName = camera.name;
  73360. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73361. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73362. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73363. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73364. });
  73365. }
  73366. }
  73367. }
  73368. };
  73369. /**
  73370. * Disables the effect on the given cameras
  73371. * @param cameras The camera to disable.
  73372. */
  73373. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73374. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73375. if (!cams) {
  73376. return;
  73377. }
  73378. for (var i = 0; i < cams.length; i++) {
  73379. var camera = cams[i];
  73380. var cameraName = camera.name;
  73381. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73382. camera.detachPostProcess(postProcess);
  73383. });
  73384. }
  73385. };
  73386. /**
  73387. * Gets a list of the post processes contained in the effect.
  73388. * @param camera The camera to get the post processes on.
  73389. * @returns The list of the post processes in the effect.
  73390. */
  73391. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73392. if (this._singleInstance) {
  73393. return this._postProcesses[0];
  73394. }
  73395. else {
  73396. if (!camera) {
  73397. return null;
  73398. }
  73399. return this._postProcesses[camera.name];
  73400. }
  73401. };
  73402. return PostProcessRenderEffect;
  73403. }());
  73404. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73405. })(BABYLON || (BABYLON = {}));
  73406. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73407. var BABYLON;
  73408. (function (BABYLON) {
  73409. var PostProcessRenderPipeline = /** @class */ (function () {
  73410. function PostProcessRenderPipeline(engine, name) {
  73411. this.engine = engine;
  73412. this._name = name;
  73413. this._renderEffects = {};
  73414. this._renderEffectsForIsolatedPass = new Array();
  73415. this._cameras = [];
  73416. }
  73417. PostProcessRenderPipeline.prototype.getClassName = function () {
  73418. return "PostProcessRenderPipeline";
  73419. };
  73420. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73421. get: function () {
  73422. for (var renderEffectName in this._renderEffects) {
  73423. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73424. if (!this._renderEffects[renderEffectName].isSupported) {
  73425. return false;
  73426. }
  73427. }
  73428. }
  73429. return true;
  73430. },
  73431. enumerable: true,
  73432. configurable: true
  73433. });
  73434. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73435. this._renderEffects[renderEffect._name] = renderEffect;
  73436. };
  73437. // private
  73438. PostProcessRenderPipeline.prototype._rebuild = function () {
  73439. };
  73440. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73441. var renderEffects = this._renderEffects[renderEffectName];
  73442. if (!renderEffects) {
  73443. return;
  73444. }
  73445. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73446. };
  73447. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73448. var renderEffects = this._renderEffects[renderEffectName];
  73449. if (!renderEffects) {
  73450. return;
  73451. }
  73452. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73453. };
  73454. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73455. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73456. if (!cams) {
  73457. return;
  73458. }
  73459. var indicesToDelete = [];
  73460. var i;
  73461. for (i = 0; i < cams.length; i++) {
  73462. var camera = cams[i];
  73463. var cameraName = camera.name;
  73464. if (this._cameras.indexOf(camera) === -1) {
  73465. this._cameras[cameraName] = camera;
  73466. }
  73467. else if (unique) {
  73468. indicesToDelete.push(i);
  73469. }
  73470. }
  73471. for (i = 0; i < indicesToDelete.length; i++) {
  73472. cameras.splice(indicesToDelete[i], 1);
  73473. }
  73474. for (var renderEffectName in this._renderEffects) {
  73475. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73476. this._renderEffects[renderEffectName]._attachCameras(cams);
  73477. }
  73478. }
  73479. };
  73480. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73481. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73482. if (!cams) {
  73483. return;
  73484. }
  73485. for (var renderEffectName in this._renderEffects) {
  73486. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73487. this._renderEffects[renderEffectName]._detachCameras(cams);
  73488. }
  73489. }
  73490. for (var i = 0; i < cams.length; i++) {
  73491. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73492. }
  73493. };
  73494. PostProcessRenderPipeline.prototype._update = function () {
  73495. for (var renderEffectName in this._renderEffects) {
  73496. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73497. this._renderEffects[renderEffectName]._update();
  73498. }
  73499. }
  73500. for (var i = 0; i < this._cameras.length; i++) {
  73501. var cameraName = this._cameras[i].name;
  73502. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73503. this._renderEffectsForIsolatedPass[cameraName]._update();
  73504. }
  73505. }
  73506. };
  73507. PostProcessRenderPipeline.prototype._reset = function () {
  73508. this._renderEffects = {};
  73509. this._renderEffectsForIsolatedPass = new Array();
  73510. };
  73511. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73512. // 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)
  73513. var effectKeys = Object.keys(this._renderEffects);
  73514. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73515. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73516. if (postProcesses) {
  73517. postProcesses[0].samples = sampleCount;
  73518. return true;
  73519. }
  73520. }
  73521. return false;
  73522. };
  73523. PostProcessRenderPipeline.prototype.dispose = function () {
  73524. // Must be implemented by children
  73525. };
  73526. __decorate([
  73527. BABYLON.serialize()
  73528. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73529. return PostProcessRenderPipeline;
  73530. }());
  73531. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73532. })(BABYLON || (BABYLON = {}));
  73533. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73534. var BABYLON;
  73535. (function (BABYLON) {
  73536. /**
  73537. * This represents a depth renderer in Babylon.
  73538. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73539. */
  73540. var DepthRenderer = /** @class */ (function () {
  73541. /**
  73542. * Instantiates a depth renderer
  73543. * @param scene The scene the renderer belongs to
  73544. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73545. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73546. */
  73547. function DepthRenderer(scene, type, camera) {
  73548. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73549. if (camera === void 0) { camera = null; }
  73550. var _this = this;
  73551. this._scene = scene;
  73552. this._camera = camera;
  73553. var engine = scene.getEngine();
  73554. // Render target
  73555. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73556. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73557. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73558. this._depthMap.refreshRate = 1;
  73559. this._depthMap.renderParticles = false;
  73560. this._depthMap.renderList = null;
  73561. // Camera to get depth map from to support multiple concurrent cameras
  73562. this._depthMap.activeCamera = this._camera;
  73563. this._depthMap.ignoreCameraViewport = true;
  73564. this._depthMap.useCameraPostProcesses = false;
  73565. // set default depth value to 1.0 (far away)
  73566. this._depthMap.onClearObservable.add(function (engine) {
  73567. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73568. });
  73569. // Custom render function
  73570. var renderSubMesh = function (subMesh) {
  73571. var mesh = subMesh.getRenderingMesh();
  73572. var scene = _this._scene;
  73573. var engine = scene.getEngine();
  73574. var material = subMesh.getMaterial();
  73575. if (!material) {
  73576. return;
  73577. }
  73578. // Culling and reverse (right handed system)
  73579. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73580. // Managing instances
  73581. var batch = mesh._getInstancesRenderList(subMesh._id);
  73582. if (batch.mustReturn) {
  73583. return;
  73584. }
  73585. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73586. var camera = _this._camera || scene.activeCamera;
  73587. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73588. engine.enableEffect(_this._effect);
  73589. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73590. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73591. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73592. // Alpha test
  73593. if (material && material.needAlphaTesting()) {
  73594. var alphaTexture = material.getAlphaTestTexture();
  73595. if (alphaTexture) {
  73596. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73597. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73598. }
  73599. }
  73600. // Bones
  73601. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73602. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73603. }
  73604. // Draw
  73605. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73606. }
  73607. };
  73608. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73609. var index;
  73610. if (depthOnlySubMeshes.length) {
  73611. engine.setColorWrite(false);
  73612. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73613. renderSubMesh(depthOnlySubMeshes.data[index]);
  73614. }
  73615. engine.setColorWrite(true);
  73616. }
  73617. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73618. renderSubMesh(opaqueSubMeshes.data[index]);
  73619. }
  73620. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73621. renderSubMesh(alphaTestSubMeshes.data[index]);
  73622. }
  73623. };
  73624. }
  73625. /**
  73626. * Creates the depth rendering effect and checks if the effect is ready.
  73627. * @param subMesh The submesh to be used to render the depth map of
  73628. * @param useInstances If multiple world instances should be used
  73629. * @returns if the depth renderer is ready to render the depth map
  73630. */
  73631. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73632. var material = subMesh.getMaterial();
  73633. if (material.disableDepthWrite) {
  73634. return false;
  73635. }
  73636. var defines = [];
  73637. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73638. var mesh = subMesh.getMesh();
  73639. // Alpha test
  73640. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73641. defines.push("#define ALPHATEST");
  73642. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73643. attribs.push(BABYLON.VertexBuffer.UVKind);
  73644. defines.push("#define UV1");
  73645. }
  73646. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73647. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73648. defines.push("#define UV2");
  73649. }
  73650. }
  73651. // Bones
  73652. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73653. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73654. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73655. if (mesh.numBoneInfluencers > 4) {
  73656. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73657. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73658. }
  73659. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73660. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73661. }
  73662. else {
  73663. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73664. }
  73665. // Instances
  73666. if (useInstances) {
  73667. defines.push("#define INSTANCES");
  73668. attribs.push("world0");
  73669. attribs.push("world1");
  73670. attribs.push("world2");
  73671. attribs.push("world3");
  73672. }
  73673. // Get correct effect
  73674. var join = defines.join("\n");
  73675. if (this._cachedDefines !== join) {
  73676. this._cachedDefines = join;
  73677. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73678. }
  73679. return this._effect.isReady();
  73680. };
  73681. /**
  73682. * Gets the texture which the depth map will be written to.
  73683. * @returns The depth map texture
  73684. */
  73685. DepthRenderer.prototype.getDepthMap = function () {
  73686. return this._depthMap;
  73687. };
  73688. /**
  73689. * Disposes of the depth renderer.
  73690. */
  73691. DepthRenderer.prototype.dispose = function () {
  73692. this._depthMap.dispose();
  73693. };
  73694. return DepthRenderer;
  73695. }());
  73696. BABYLON.DepthRenderer = DepthRenderer;
  73697. })(BABYLON || (BABYLON = {}));
  73698. //# sourceMappingURL=babylon.depthRenderer.js.map
  73699. var BABYLON;
  73700. (function (BABYLON) {
  73701. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73702. __extends(SSAORenderingPipeline, _super);
  73703. /**
  73704. * @constructor
  73705. * @param {string} name - The rendering pipeline name
  73706. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73707. * @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 }
  73708. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73709. */
  73710. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73711. var _this = _super.call(this, scene.getEngine(), name) || this;
  73712. // Members
  73713. /**
  73714. * The PassPostProcess id in the pipeline that contains the original scene color
  73715. */
  73716. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73717. /**
  73718. * The SSAO PostProcess id in the pipeline
  73719. */
  73720. _this.SSAORenderEffect = "SSAORenderEffect";
  73721. /**
  73722. * The horizontal blur PostProcess id in the pipeline
  73723. */
  73724. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73725. /**
  73726. * The vertical blur PostProcess id in the pipeline
  73727. */
  73728. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73729. /**
  73730. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73731. */
  73732. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73733. /**
  73734. * The output strength of the SSAO post-process. Default value is 1.0.
  73735. */
  73736. _this.totalStrength = 1.0;
  73737. /**
  73738. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73739. */
  73740. _this.radius = 0.0001;
  73741. /**
  73742. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73743. * Must not be equal to fallOff and superior to fallOff.
  73744. * Default value is 0.975
  73745. */
  73746. _this.area = 0.0075;
  73747. /**
  73748. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73749. * Must not be equal to area and inferior to area.
  73750. * Default value is 0.0
  73751. */
  73752. _this.fallOff = 0.000001;
  73753. /**
  73754. * The base color of the SSAO post-process
  73755. * The final result is "base + ssao" between [0, 1]
  73756. */
  73757. _this.base = 0.5;
  73758. _this._firstUpdate = true;
  73759. _this._scene = scene;
  73760. // Set up assets
  73761. _this._createRandomTexture();
  73762. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73763. var ssaoRatio = ratio.ssaoRatio || ratio;
  73764. var combineRatio = ratio.combineRatio || ratio;
  73765. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73766. _this._createSSAOPostProcess(ssaoRatio);
  73767. _this._createBlurPostProcess(ssaoRatio);
  73768. _this._createSSAOCombinePostProcess(combineRatio);
  73769. // Set up pipeline
  73770. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73771. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73772. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73774. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73775. // Finish
  73776. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73777. if (cameras)
  73778. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73779. return _this;
  73780. }
  73781. // Public Methods
  73782. /**
  73783. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73784. */
  73785. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73786. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73787. for (var i = 0; i < this._scene.cameras.length; i++) {
  73788. var camera = this._scene.cameras[i];
  73789. this._originalColorPostProcess.dispose(camera);
  73790. this._ssaoPostProcess.dispose(camera);
  73791. this._blurHPostProcess.dispose(camera);
  73792. this._blurVPostProcess.dispose(camera);
  73793. this._ssaoCombinePostProcess.dispose(camera);
  73794. }
  73795. this._randomTexture.dispose();
  73796. if (disableDepthRender)
  73797. this._scene.disableDepthRenderer();
  73798. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73799. _super.prototype.dispose.call(this);
  73800. };
  73801. // Private Methods
  73802. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73803. var _this = this;
  73804. var size = 16;
  73805. 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);
  73806. 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);
  73807. this._blurHPostProcess.onActivateObservable.add(function () {
  73808. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73809. _this._blurHPostProcess.kernel = size * dw;
  73810. });
  73811. this._blurVPostProcess.onActivateObservable.add(function () {
  73812. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73813. _this._blurVPostProcess.kernel = size * dw;
  73814. });
  73815. };
  73816. SSAORenderingPipeline.prototype._rebuild = function () {
  73817. this._firstUpdate = true;
  73818. _super.prototype._rebuild.call(this);
  73819. };
  73820. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73821. var _this = this;
  73822. var numSamples = 16;
  73823. var sampleSphere = [
  73824. 0.5381, 0.1856, -0.4319,
  73825. 0.1379, 0.2486, 0.4430,
  73826. 0.3371, 0.5679, -0.0057,
  73827. -0.6999, -0.0451, -0.0019,
  73828. 0.0689, -0.1598, -0.8547,
  73829. 0.0560, 0.0069, -0.1843,
  73830. -0.0146, 0.1402, 0.0762,
  73831. 0.0100, -0.1924, -0.0344,
  73832. -0.3577, -0.5301, -0.4358,
  73833. -0.3169, 0.1063, 0.0158,
  73834. 0.0103, -0.5869, 0.0046,
  73835. -0.0897, -0.4940, 0.3287,
  73836. 0.7119, -0.0154, -0.0918,
  73837. -0.0533, 0.0596, -0.5411,
  73838. 0.0352, -0.0631, 0.5460,
  73839. -0.4776, 0.2847, -0.0271
  73840. ];
  73841. var samplesFactor = 1.0 / numSamples;
  73842. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73843. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73844. "area", "fallOff", "base", "range", "viewport"
  73845. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73846. this._ssaoPostProcess.onApply = function (effect) {
  73847. if (_this._firstUpdate) {
  73848. effect.setArray3("sampleSphere", sampleSphere);
  73849. effect.setFloat("samplesFactor", samplesFactor);
  73850. effect.setFloat("randTextureTiles", 4.0);
  73851. }
  73852. effect.setFloat("totalStrength", _this.totalStrength);
  73853. effect.setFloat("radius", _this.radius);
  73854. effect.setFloat("area", _this.area);
  73855. effect.setFloat("fallOff", _this.fallOff);
  73856. effect.setFloat("base", _this.base);
  73857. effect.setTexture("textureSampler", _this._depthTexture);
  73858. effect.setTexture("randomSampler", _this._randomTexture);
  73859. };
  73860. };
  73861. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73862. var _this = this;
  73863. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73864. this._ssaoCombinePostProcess.onApply = function (effect) {
  73865. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73866. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73867. };
  73868. };
  73869. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73870. var size = 512;
  73871. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73872. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73873. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73874. var context = this._randomTexture.getContext();
  73875. var rand = function (min, max) {
  73876. return Math.random() * (max - min) + min;
  73877. };
  73878. var randVector = BABYLON.Vector3.Zero();
  73879. for (var x = 0; x < size; x++) {
  73880. for (var y = 0; y < size; y++) {
  73881. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73882. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73883. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73884. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73885. context.fillRect(x, y, 1, 1);
  73886. }
  73887. }
  73888. this._randomTexture.update(false);
  73889. };
  73890. __decorate([
  73891. BABYLON.serialize()
  73892. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73893. __decorate([
  73894. BABYLON.serialize()
  73895. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73896. __decorate([
  73897. BABYLON.serialize()
  73898. ], SSAORenderingPipeline.prototype, "area", void 0);
  73899. __decorate([
  73900. BABYLON.serialize()
  73901. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73902. __decorate([
  73903. BABYLON.serialize()
  73904. ], SSAORenderingPipeline.prototype, "base", void 0);
  73905. return SSAORenderingPipeline;
  73906. }(BABYLON.PostProcessRenderPipeline));
  73907. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73908. })(BABYLON || (BABYLON = {}));
  73909. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73910. var BABYLON;
  73911. (function (BABYLON) {
  73912. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73913. __extends(SSAO2RenderingPipeline, _super);
  73914. /**
  73915. * @constructor
  73916. * @param {string} name - The rendering pipeline name
  73917. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73918. * @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 }
  73919. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73920. */
  73921. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73922. var _this = _super.call(this, scene.getEngine(), name) || this;
  73923. // Members
  73924. /**
  73925. * The PassPostProcess id in the pipeline that contains the original scene color
  73926. */
  73927. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73928. /**
  73929. * The SSAO PostProcess id in the pipeline
  73930. */
  73931. _this.SSAORenderEffect = "SSAORenderEffect";
  73932. /**
  73933. * The horizontal blur PostProcess id in the pipeline
  73934. */
  73935. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73936. /**
  73937. * The vertical blur PostProcess id in the pipeline
  73938. */
  73939. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73940. /**
  73941. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73942. */
  73943. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73944. /**
  73945. * The output strength of the SSAO post-process. Default value is 1.0.
  73946. */
  73947. _this.totalStrength = 1.0;
  73948. /**
  73949. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73950. */
  73951. _this.maxZ = 100.0;
  73952. /**
  73953. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73954. */
  73955. _this.minZAspect = 0.2;
  73956. /**
  73957. * Number of samples used for the SSAO calculations. Default value is 8
  73958. */
  73959. _this._samples = 8;
  73960. /**
  73961. * Are we using bilateral blur ?
  73962. */
  73963. _this._expensiveBlur = true;
  73964. /**
  73965. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73966. */
  73967. _this.radius = 2.0;
  73968. /**
  73969. * The base color of the SSAO post-process
  73970. * The final result is "base + ssao" between [0, 1]
  73971. */
  73972. _this.base = 0.1;
  73973. _this._firstUpdate = true;
  73974. _this._scene = scene;
  73975. _this._ratio = ratio;
  73976. if (!_this.isSupported) {
  73977. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73978. return _this;
  73979. }
  73980. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73981. var blurRatio = _this._ratio.blurRatio || ratio;
  73982. // Set up assets
  73983. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73984. _this._createRandomTexture();
  73985. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73986. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73987. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73988. _this._createSSAOPostProcess(1.0);
  73989. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73990. _this._createSSAOCombinePostProcess(blurRatio);
  73991. // Set up pipeline
  73992. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73993. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73994. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73995. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73996. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73997. // Finish
  73998. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73999. if (cameras)
  74000. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74001. return _this;
  74002. }
  74003. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74004. get: function () {
  74005. return this._samples;
  74006. },
  74007. set: function (n) {
  74008. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74009. this._samples = n;
  74010. this._sampleSphere = this._generateHemisphere();
  74011. this._firstUpdate = true;
  74012. },
  74013. enumerable: true,
  74014. configurable: true
  74015. });
  74016. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74017. get: function () {
  74018. return this._expensiveBlur;
  74019. },
  74020. set: function (b) {
  74021. 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"]);
  74022. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74023. this._expensiveBlur = b;
  74024. this._firstUpdate = true;
  74025. },
  74026. enumerable: true,
  74027. configurable: true
  74028. });
  74029. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74030. /**
  74031. * Support test.
  74032. */
  74033. get: function () {
  74034. var engine = BABYLON.Engine.LastCreatedEngine;
  74035. if (!engine) {
  74036. return false;
  74037. }
  74038. return engine.getCaps().drawBuffersExtension;
  74039. },
  74040. enumerable: true,
  74041. configurable: true
  74042. });
  74043. // Public Methods
  74044. /**
  74045. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74046. */
  74047. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74048. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74049. for (var i = 0; i < this._scene.cameras.length; i++) {
  74050. var camera = this._scene.cameras[i];
  74051. this._originalColorPostProcess.dispose(camera);
  74052. this._ssaoPostProcess.dispose(camera);
  74053. this._blurHPostProcess.dispose(camera);
  74054. this._blurVPostProcess.dispose(camera);
  74055. this._ssaoCombinePostProcess.dispose(camera);
  74056. }
  74057. this._randomTexture.dispose();
  74058. if (disableGeometryBufferRenderer)
  74059. this._scene.disableGeometryBufferRenderer();
  74060. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74061. _super.prototype.dispose.call(this);
  74062. };
  74063. // Private Methods
  74064. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74065. var _this = this;
  74066. this._samplerOffsets = [];
  74067. var expensive = this.expensiveBlur;
  74068. for (var i = -8; i < 8; i++) {
  74069. this._samplerOffsets.push(i * 2 + 0.5);
  74070. }
  74071. 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");
  74072. this._blurHPostProcess.onApply = function (effect) {
  74073. if (!_this._scene.activeCamera) {
  74074. return;
  74075. }
  74076. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74077. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74078. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74079. effect.setFloat("radius", _this.radius);
  74080. effect.setTexture("depthSampler", _this._depthTexture);
  74081. if (_this._firstUpdate) {
  74082. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74083. }
  74084. };
  74085. 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");
  74086. this._blurVPostProcess.onApply = function (effect) {
  74087. if (!_this._scene.activeCamera) {
  74088. return;
  74089. }
  74090. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74091. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74092. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74093. effect.setFloat("radius", _this.radius);
  74094. effect.setTexture("depthSampler", _this._depthTexture);
  74095. if (_this._firstUpdate) {
  74096. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74097. _this._firstUpdate = false;
  74098. }
  74099. };
  74100. };
  74101. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74102. this._firstUpdate = true;
  74103. _super.prototype._rebuild.call(this);
  74104. };
  74105. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74106. var numSamples = this.samples;
  74107. var result = [];
  74108. var vector, scale;
  74109. var rand = function (min, max) {
  74110. return Math.random() * (max - min) + min;
  74111. };
  74112. var i = 0;
  74113. while (i < numSamples) {
  74114. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74115. vector.normalize();
  74116. scale = i / numSamples;
  74117. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74118. vector.scaleInPlace(scale);
  74119. result.push(vector.x, vector.y, vector.z);
  74120. i++;
  74121. }
  74122. return result;
  74123. };
  74124. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74125. var _this = this;
  74126. var numSamples = this.samples;
  74127. this._sampleSphere = this._generateHemisphere();
  74128. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74129. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74130. "base", "range", "projection", "near", "far", "texelSize",
  74131. "xViewport", "yViewport", "maxZ", "minZAspect"
  74132. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74133. this._ssaoPostProcess.onApply = function (effect) {
  74134. if (_this._firstUpdate) {
  74135. effect.setArray3("sampleSphere", _this._sampleSphere);
  74136. effect.setFloat("randTextureTiles", 4.0);
  74137. }
  74138. if (!_this._scene.activeCamera) {
  74139. return;
  74140. }
  74141. effect.setFloat("samplesFactor", 1 / _this.samples);
  74142. effect.setFloat("totalStrength", _this.totalStrength);
  74143. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74144. effect.setFloat("radius", _this.radius);
  74145. effect.setFloat("maxZ", _this.maxZ);
  74146. effect.setFloat("minZAspect", _this.minZAspect);
  74147. effect.setFloat("base", _this.base);
  74148. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74149. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74150. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74151. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74152. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74153. effect.setTexture("textureSampler", _this._depthTexture);
  74154. effect.setTexture("normalSampler", _this._normalTexture);
  74155. effect.setTexture("randomSampler", _this._randomTexture);
  74156. };
  74157. };
  74158. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74159. var _this = this;
  74160. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74161. this._ssaoCombinePostProcess.onApply = function (effect) {
  74162. var viewport = _this._scene.activeCamera.viewport;
  74163. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74164. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74165. };
  74166. };
  74167. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74168. var size = 512;
  74169. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74170. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74171. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74172. var context = this._randomTexture.getContext();
  74173. var rand = function (min, max) {
  74174. return Math.random() * (max - min) + min;
  74175. };
  74176. var randVector = BABYLON.Vector3.Zero();
  74177. for (var x = 0; x < size; x++) {
  74178. for (var y = 0; y < size; y++) {
  74179. randVector.x = rand(0.0, 1.0);
  74180. randVector.y = rand(0.0, 1.0);
  74181. randVector.z = 0.0;
  74182. randVector.normalize();
  74183. randVector.scaleInPlace(255);
  74184. randVector.x = Math.floor(randVector.x);
  74185. randVector.y = Math.floor(randVector.y);
  74186. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74187. context.fillRect(x, y, 1, 1);
  74188. }
  74189. }
  74190. this._randomTexture.update(false);
  74191. };
  74192. /**
  74193. * Serialize the rendering pipeline (Used when exporting)
  74194. * @returns the serialized object
  74195. */
  74196. SSAO2RenderingPipeline.prototype.serialize = function () {
  74197. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74198. serializationObject.customType = "SSAO2RenderingPipeline";
  74199. return serializationObject;
  74200. };
  74201. /**
  74202. * Parse the serialized pipeline
  74203. * @param source Source pipeline.
  74204. * @param scene The scene to load the pipeline to.
  74205. * @param rootUrl The URL of the serialized pipeline.
  74206. * @returns An instantiated pipeline from the serialized object.
  74207. */
  74208. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74209. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74210. };
  74211. __decorate([
  74212. BABYLON.serialize()
  74213. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74214. __decorate([
  74215. BABYLON.serialize()
  74216. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74217. __decorate([
  74218. BABYLON.serialize()
  74219. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74220. __decorate([
  74221. BABYLON.serialize("samples")
  74222. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74223. __decorate([
  74224. BABYLON.serialize()
  74225. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74226. __decorate([
  74227. BABYLON.serialize("expensiveBlur")
  74228. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74229. __decorate([
  74230. BABYLON.serialize()
  74231. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74232. __decorate([
  74233. BABYLON.serialize()
  74234. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74235. return SSAO2RenderingPipeline;
  74236. }(BABYLON.PostProcessRenderPipeline));
  74237. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74238. })(BABYLON || (BABYLON = {}));
  74239. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74240. // BABYLON.JS Chromatic Aberration GLSL Shader
  74241. // Author: Olivier Guyot
  74242. // Separates very slightly R, G and B colors on the edges of the screen
  74243. // Inspired by Francois Tarlier & Martins Upitis
  74244. var BABYLON;
  74245. (function (BABYLON) {
  74246. var LensRenderingPipeline = /** @class */ (function (_super) {
  74247. __extends(LensRenderingPipeline, _super);
  74248. /**
  74249. * @constructor
  74250. *
  74251. * Effect parameters are as follow:
  74252. * {
  74253. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74254. * edge_blur: number; // from 0 to x (1 for realism)
  74255. * distortion: number; // from 0 to x (1 for realism)
  74256. * grain_amount: number; // from 0 to 1
  74257. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74258. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74259. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74260. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74261. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74262. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74263. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74264. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74265. * }
  74266. * Note: if an effect parameter is unset, effect is disabled
  74267. *
  74268. * @param {string} name - The rendering pipeline name
  74269. * @param {object} parameters - An object containing all parameters (see above)
  74270. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74271. * @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)
  74272. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74273. */
  74274. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74275. if (ratio === void 0) { ratio = 1.0; }
  74276. var _this = _super.call(this, scene.getEngine(), name) || this;
  74277. // Lens effects can be of the following:
  74278. // - chromatic aberration (slight shift of RGB colors)
  74279. // - blur on the edge of the lens
  74280. // - lens distortion
  74281. // - depth-of-field blur & highlights enhancing
  74282. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74283. // - grain effect (noise or custom texture)
  74284. // Two additional texture samplers are needed:
  74285. // - depth map (for depth-of-field)
  74286. // - grain texture
  74287. /**
  74288. * The chromatic aberration PostProcess id in the pipeline
  74289. */
  74290. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74291. /**
  74292. * The highlights enhancing PostProcess id in the pipeline
  74293. */
  74294. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74295. /**
  74296. * The depth-of-field PostProcess id in the pipeline
  74297. */
  74298. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74299. _this._scene = scene;
  74300. // Fetch texture samplers
  74301. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74302. if (parameters.grain_texture) {
  74303. _this._grainTexture = parameters.grain_texture;
  74304. }
  74305. else {
  74306. _this._createGrainTexture();
  74307. }
  74308. // save parameters
  74309. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74310. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74311. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74312. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74313. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74314. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74315. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74316. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74317. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74318. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74319. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74320. // Create effects
  74321. _this._createChromaticAberrationPostProcess(ratio);
  74322. _this._createHighlightsPostProcess(ratio);
  74323. _this._createDepthOfFieldPostProcess(ratio / 4);
  74324. // Set up pipeline
  74325. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74326. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74327. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74328. if (_this._highlightsGain === -1) {
  74329. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74330. }
  74331. // Finish
  74332. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74333. if (cameras) {
  74334. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74335. }
  74336. return _this;
  74337. }
  74338. // public methods (self explanatory)
  74339. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74340. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74341. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74342. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74343. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74344. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74345. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74346. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74347. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74348. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74349. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74350. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74351. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74352. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74353. };
  74354. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74355. this._highlightsPostProcess.updateEffect();
  74356. };
  74357. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74358. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74359. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74360. this._highlightsGain = amount;
  74361. };
  74362. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74363. if (this._highlightsGain === -1) {
  74364. this._highlightsGain = 1.0;
  74365. }
  74366. this._highlightsThreshold = amount;
  74367. };
  74368. LensRenderingPipeline.prototype.disableHighlights = function () {
  74369. this._highlightsGain = -1;
  74370. };
  74371. /**
  74372. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74373. */
  74374. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74375. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74376. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74377. this._chromaticAberrationPostProcess = null;
  74378. this._highlightsPostProcess = null;
  74379. this._depthOfFieldPostProcess = null;
  74380. this._grainTexture.dispose();
  74381. if (disableDepthRender)
  74382. this._scene.disableDepthRenderer();
  74383. };
  74384. // colors shifting and distortion
  74385. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74386. var _this = this;
  74387. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74388. [], // samplers
  74389. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74390. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74391. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74392. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74393. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74394. effect.setFloat('radialIntensity', 1);
  74395. effect.setFloat2('direction', 17, 17);
  74396. effect.setFloat2('centerPosition', 0.5, 0.5);
  74397. };
  74398. };
  74399. // highlights enhancing
  74400. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74401. var _this = this;
  74402. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74403. [], // samplers
  74404. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74405. this._highlightsPostProcess.onApply = function (effect) {
  74406. effect.setFloat('gain', _this._highlightsGain);
  74407. effect.setFloat('threshold', _this._highlightsThreshold);
  74408. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74409. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74410. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74411. };
  74412. };
  74413. // colors shifting and distortion
  74414. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74415. var _this = this;
  74416. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74417. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74418. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74419. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74420. this._depthOfFieldPostProcess.onApply = function (effect) {
  74421. effect.setTexture("depthSampler", _this._depthTexture);
  74422. effect.setTexture("grainSampler", _this._grainTexture);
  74423. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74424. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74425. effect.setFloat('grain_amount', _this._grainAmount);
  74426. effect.setBool('blur_noise', _this._blurNoise);
  74427. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74428. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74429. effect.setFloat('distortion', _this._distortion);
  74430. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74431. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74432. effect.setFloat('aperture', _this._dofAperture);
  74433. effect.setFloat('darken', _this._dofDarken);
  74434. effect.setFloat('edge_blur', _this._edgeBlur);
  74435. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74436. if (_this._scene.activeCamera) {
  74437. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74438. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74439. }
  74440. };
  74441. };
  74442. // creates a black and white random noise texture, 512x512
  74443. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74444. var size = 512;
  74445. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74446. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74447. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74448. var context = this._grainTexture.getContext();
  74449. var rand = function (min, max) {
  74450. return Math.random() * (max - min) + min;
  74451. };
  74452. var value;
  74453. for (var x = 0; x < size; x++) {
  74454. for (var y = 0; y < size; y++) {
  74455. value = Math.floor(rand(0.42, 0.58) * 255);
  74456. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74457. context.fillRect(x, y, 1, 1);
  74458. }
  74459. }
  74460. this._grainTexture.update(false);
  74461. };
  74462. return LensRenderingPipeline;
  74463. }(BABYLON.PostProcessRenderPipeline));
  74464. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74465. })(BABYLON || (BABYLON = {}));
  74466. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74467. var BABYLON;
  74468. (function (BABYLON) {
  74469. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74470. __extends(StandardRenderingPipeline, _super);
  74471. /**
  74472. * @constructor
  74473. * @param {string} name - The rendering pipeline name
  74474. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74475. * @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)
  74476. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74477. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74478. */
  74479. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74480. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74481. var _this = _super.call(this, scene.getEngine(), name) || this;
  74482. _this.downSampleX4PostProcess = null;
  74483. _this.brightPassPostProcess = null;
  74484. _this.blurHPostProcesses = [];
  74485. _this.blurVPostProcesses = [];
  74486. _this.textureAdderPostProcess = null;
  74487. _this.volumetricLightPostProcess = null;
  74488. _this.volumetricLightSmoothXPostProcess = null;
  74489. _this.volumetricLightSmoothYPostProcess = null;
  74490. _this.volumetricLightMergePostProces = null;
  74491. _this.volumetricLightFinalPostProcess = null;
  74492. _this.luminancePostProcess = null;
  74493. _this.luminanceDownSamplePostProcesses = [];
  74494. _this.hdrPostProcess = null;
  74495. _this.textureAdderFinalPostProcess = null;
  74496. _this.lensFlareFinalPostProcess = null;
  74497. _this.hdrFinalPostProcess = null;
  74498. _this.lensFlarePostProcess = null;
  74499. _this.lensFlareComposePostProcess = null;
  74500. _this.motionBlurPostProcess = null;
  74501. _this.depthOfFieldPostProcess = null;
  74502. // Values
  74503. _this.brightThreshold = 1.0;
  74504. _this.blurWidth = 512.0;
  74505. _this.horizontalBlur = false;
  74506. _this.exposure = 1.0;
  74507. _this.lensTexture = null;
  74508. _this.volumetricLightCoefficient = 0.2;
  74509. _this.volumetricLightPower = 4.0;
  74510. _this.volumetricLightBlurScale = 64.0;
  74511. _this.sourceLight = null;
  74512. _this.hdrMinimumLuminance = 1.0;
  74513. _this.hdrDecreaseRate = 0.5;
  74514. _this.hdrIncreaseRate = 0.5;
  74515. _this.lensColorTexture = null;
  74516. _this.lensFlareStrength = 20.0;
  74517. _this.lensFlareGhostDispersal = 1.4;
  74518. _this.lensFlareHaloWidth = 0.7;
  74519. _this.lensFlareDistortionStrength = 16.0;
  74520. _this.lensStarTexture = null;
  74521. _this.lensFlareDirtTexture = null;
  74522. _this.depthOfFieldDistance = 10.0;
  74523. _this.depthOfFieldBlurWidth = 64.0;
  74524. _this.motionStrength = 1.0;
  74525. // IAnimatable
  74526. _this.animations = [];
  74527. _this._currentDepthOfFieldSource = null;
  74528. _this._hdrCurrentLuminance = 1.0;
  74529. // Getters and setters
  74530. _this._bloomEnabled = true;
  74531. _this._depthOfFieldEnabled = false;
  74532. _this._vlsEnabled = false;
  74533. _this._lensFlareEnabled = false;
  74534. _this._hdrEnabled = false;
  74535. _this._motionBlurEnabled = false;
  74536. _this._motionBlurSamples = 64.0;
  74537. _this._volumetricLightStepsCount = 50.0;
  74538. _this._cameras = cameras || [];
  74539. // Initialize
  74540. _this._scene = scene;
  74541. _this._basePostProcess = originalPostProcess;
  74542. _this._ratio = ratio;
  74543. // Misc
  74544. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74545. // Finish
  74546. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74547. _this._buildPipeline();
  74548. return _this;
  74549. }
  74550. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74551. get: function () {
  74552. return this._bloomEnabled;
  74553. },
  74554. set: function (enabled) {
  74555. if (this._bloomEnabled === enabled) {
  74556. return;
  74557. }
  74558. this._bloomEnabled = enabled;
  74559. this._buildPipeline();
  74560. },
  74561. enumerable: true,
  74562. configurable: true
  74563. });
  74564. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74565. get: function () {
  74566. return this._depthOfFieldEnabled;
  74567. },
  74568. set: function (enabled) {
  74569. if (this._depthOfFieldEnabled === enabled) {
  74570. return;
  74571. }
  74572. this._depthOfFieldEnabled = enabled;
  74573. this._buildPipeline();
  74574. },
  74575. enumerable: true,
  74576. configurable: true
  74577. });
  74578. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74579. get: function () {
  74580. return this._lensFlareEnabled;
  74581. },
  74582. set: function (enabled) {
  74583. if (this._lensFlareEnabled === enabled) {
  74584. return;
  74585. }
  74586. this._lensFlareEnabled = enabled;
  74587. this._buildPipeline();
  74588. },
  74589. enumerable: true,
  74590. configurable: true
  74591. });
  74592. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74593. get: function () {
  74594. return this._hdrEnabled;
  74595. },
  74596. set: function (enabled) {
  74597. if (this._hdrEnabled === enabled) {
  74598. return;
  74599. }
  74600. this._hdrEnabled = enabled;
  74601. this._buildPipeline();
  74602. },
  74603. enumerable: true,
  74604. configurable: true
  74605. });
  74606. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74607. get: function () {
  74608. return this._vlsEnabled;
  74609. },
  74610. set: function (enabled) {
  74611. if (this._vlsEnabled === enabled) {
  74612. return;
  74613. }
  74614. if (enabled) {
  74615. var geometry = this._scene.enableGeometryBufferRenderer();
  74616. if (!geometry) {
  74617. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74618. return;
  74619. }
  74620. }
  74621. this._vlsEnabled = enabled;
  74622. this._buildPipeline();
  74623. },
  74624. enumerable: true,
  74625. configurable: true
  74626. });
  74627. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74628. get: function () {
  74629. return this._motionBlurEnabled;
  74630. },
  74631. set: function (enabled) {
  74632. if (this._motionBlurEnabled === enabled) {
  74633. return;
  74634. }
  74635. this._motionBlurEnabled = enabled;
  74636. this._buildPipeline();
  74637. },
  74638. enumerable: true,
  74639. configurable: true
  74640. });
  74641. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74642. get: function () {
  74643. return this._volumetricLightStepsCount;
  74644. },
  74645. set: function (count) {
  74646. if (this.volumetricLightPostProcess) {
  74647. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74648. }
  74649. this._volumetricLightStepsCount = count;
  74650. },
  74651. enumerable: true,
  74652. configurable: true
  74653. });
  74654. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74655. get: function () {
  74656. return this._motionBlurSamples;
  74657. },
  74658. set: function (samples) {
  74659. if (this.motionBlurPostProcess) {
  74660. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74661. }
  74662. this._motionBlurSamples = samples;
  74663. },
  74664. enumerable: true,
  74665. configurable: true
  74666. });
  74667. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74668. var _this = this;
  74669. var ratio = this._ratio;
  74670. var scene = this._scene;
  74671. this._disposePostProcesses();
  74672. this._reset();
  74673. // Create pass post-process
  74674. if (!this._basePostProcess) {
  74675. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74676. this.originalPostProcess.onApply = function (effect) {
  74677. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74678. };
  74679. }
  74680. else {
  74681. this.originalPostProcess = this._basePostProcess;
  74682. }
  74683. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74684. this._currentDepthOfFieldSource = this.originalPostProcess;
  74685. if (this._bloomEnabled) {
  74686. // Create down sample X4 post-process
  74687. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74688. // Create bright pass post-process
  74689. this._createBrightPassPostProcess(scene, ratio / 2);
  74690. // Create gaussian blur post-processes (down sampling blurs)
  74691. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74692. // Create texture adder post-process
  74693. this._createTextureAdderPostProcess(scene, ratio);
  74694. // Create depth-of-field source post-process
  74695. 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);
  74696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74697. }
  74698. if (this._vlsEnabled) {
  74699. // Create volumetric light
  74700. this._createVolumetricLightPostProcess(scene, ratio);
  74701. // Create volumetric light final post-process
  74702. 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);
  74703. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74704. }
  74705. if (this._lensFlareEnabled) {
  74706. // Create lens flare post-process
  74707. this._createLensFlarePostProcess(scene, ratio);
  74708. // Create depth-of-field source post-process post lens-flare and disable it now
  74709. 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);
  74710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74711. }
  74712. if (this._hdrEnabled) {
  74713. // Create luminance
  74714. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74715. // Create HDR
  74716. this._createHdrPostProcess(scene, ratio);
  74717. // Create depth-of-field source post-process post hdr and disable it now
  74718. 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);
  74719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74720. }
  74721. if (this._depthOfFieldEnabled) {
  74722. // Create gaussian blur used by depth-of-field
  74723. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74724. // Create depth-of-field post-process
  74725. this._createDepthOfFieldPostProcess(scene, ratio);
  74726. }
  74727. if (this._motionBlurEnabled) {
  74728. // Create motion blur post-process
  74729. this._createMotionBlurPostProcess(scene, ratio);
  74730. }
  74731. if (this._cameras !== null) {
  74732. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74733. }
  74734. };
  74735. // Down Sample X4 Post-Processs
  74736. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74737. var _this = this;
  74738. var downSampleX4Offsets = new Array(32);
  74739. 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);
  74740. this.downSampleX4PostProcess.onApply = function (effect) {
  74741. var id = 0;
  74742. var width = _this.downSampleX4PostProcess.width;
  74743. var height = _this.downSampleX4PostProcess.height;
  74744. for (var i = -2; i < 2; i++) {
  74745. for (var j = -2; j < 2; j++) {
  74746. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74747. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74748. id += 2;
  74749. }
  74750. }
  74751. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74752. };
  74753. // Add to pipeline
  74754. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74755. };
  74756. // Brightpass Post-Process
  74757. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74758. var _this = this;
  74759. var brightOffsets = new Array(8);
  74760. 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);
  74761. this.brightPassPostProcess.onApply = function (effect) {
  74762. var sU = (1.0 / _this.brightPassPostProcess.width);
  74763. var sV = (1.0 / _this.brightPassPostProcess.height);
  74764. brightOffsets[0] = -0.5 * sU;
  74765. brightOffsets[1] = 0.5 * sV;
  74766. brightOffsets[2] = 0.5 * sU;
  74767. brightOffsets[3] = 0.5 * sV;
  74768. brightOffsets[4] = -0.5 * sU;
  74769. brightOffsets[5] = -0.5 * sV;
  74770. brightOffsets[6] = 0.5 * sU;
  74771. brightOffsets[7] = -0.5 * sV;
  74772. effect.setArray2("dsOffsets", brightOffsets);
  74773. effect.setFloat("brightThreshold", _this.brightThreshold);
  74774. };
  74775. // Add to pipeline
  74776. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74777. };
  74778. // Create blur H&V post-processes
  74779. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74780. var _this = this;
  74781. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74782. var engine = scene.getEngine();
  74783. 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);
  74784. 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);
  74785. blurX.onActivateObservable.add(function () {
  74786. var dw = blurX.width / engine.getRenderWidth();
  74787. blurX.kernel = _this[blurWidthKey] * dw;
  74788. });
  74789. blurY.onActivateObservable.add(function () {
  74790. var dw = blurY.height / engine.getRenderHeight();
  74791. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74792. });
  74793. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74795. this.blurHPostProcesses.push(blurX);
  74796. this.blurVPostProcesses.push(blurY);
  74797. };
  74798. // Create texture adder post-process
  74799. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74800. var _this = this;
  74801. 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);
  74802. this.textureAdderPostProcess.onApply = function (effect) {
  74803. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74804. effect.setTexture("lensSampler", _this.lensTexture);
  74805. effect.setFloat("exposure", _this.exposure);
  74806. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74807. };
  74808. // Add to pipeline
  74809. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74810. };
  74811. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74812. var _this = this;
  74813. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74814. geometryRenderer.enablePosition = true;
  74815. var geometry = geometryRenderer.getGBuffer();
  74816. // Base post-process
  74817. 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));
  74818. var depthValues = BABYLON.Vector2.Zero();
  74819. this.volumetricLightPostProcess.onApply = function (effect) {
  74820. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74821. var generator = _this.sourceLight.getShadowGenerator();
  74822. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74823. effect.setTexture("positionSampler", geometry.textures[2]);
  74824. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74825. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74826. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74827. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74828. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74829. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74830. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74831. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74832. effect.setVector2("depthValues", depthValues);
  74833. }
  74834. };
  74835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74836. // Smooth
  74837. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74838. // Merge
  74839. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74840. this.volumetricLightMergePostProces.onApply = function (effect) {
  74841. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74842. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74843. };
  74844. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74845. };
  74846. // Create luminance
  74847. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74848. var _this = this;
  74849. // Create luminance
  74850. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74851. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74852. var offsets = [];
  74853. this.luminancePostProcess.onApply = function (effect) {
  74854. var sU = (1.0 / _this.luminancePostProcess.width);
  74855. var sV = (1.0 / _this.luminancePostProcess.height);
  74856. offsets[0] = -0.5 * sU;
  74857. offsets[1] = 0.5 * sV;
  74858. offsets[2] = 0.5 * sU;
  74859. offsets[3] = 0.5 * sV;
  74860. offsets[4] = -0.5 * sU;
  74861. offsets[5] = -0.5 * sV;
  74862. offsets[6] = 0.5 * sU;
  74863. offsets[7] = -0.5 * sV;
  74864. effect.setArray2("lumOffsets", offsets);
  74865. };
  74866. // Add to pipeline
  74867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74868. // Create down sample luminance
  74869. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74870. var size = Math.pow(3, i);
  74871. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74872. if (i === 0) {
  74873. defines += "#define FINAL_DOWN_SAMPLER";
  74874. }
  74875. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74876. this.luminanceDownSamplePostProcesses.push(postProcess);
  74877. }
  74878. // Create callbacks and add effects
  74879. var lastLuminance = this.luminancePostProcess;
  74880. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74881. var downSampleOffsets = new Array(18);
  74882. pp.onApply = function (effect) {
  74883. if (!lastLuminance) {
  74884. return;
  74885. }
  74886. var id = 0;
  74887. for (var x = -1; x < 2; x++) {
  74888. for (var y = -1; y < 2; y++) {
  74889. downSampleOffsets[id] = x / lastLuminance.width;
  74890. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74891. id += 2;
  74892. }
  74893. }
  74894. effect.setArray2("dsOffsets", downSampleOffsets);
  74895. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74896. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74897. lastLuminance = _this.luminancePostProcess;
  74898. }
  74899. else {
  74900. lastLuminance = pp;
  74901. }
  74902. };
  74903. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74904. pp.onAfterRender = function (effect) {
  74905. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74906. 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);
  74907. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74908. };
  74909. }
  74910. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74911. });
  74912. };
  74913. // Create HDR post-process
  74914. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74915. var _this = this;
  74916. 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);
  74917. var outputLiminance = 1;
  74918. var time = 0;
  74919. var lastTime = 0;
  74920. this.hdrPostProcess.onApply = function (effect) {
  74921. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74922. time += scene.getEngine().getDeltaTime();
  74923. if (outputLiminance < 0) {
  74924. outputLiminance = _this._hdrCurrentLuminance;
  74925. }
  74926. else {
  74927. var dt = (lastTime - time) / 1000.0;
  74928. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74929. outputLiminance += _this.hdrDecreaseRate * dt;
  74930. }
  74931. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74932. outputLiminance -= _this.hdrIncreaseRate * dt;
  74933. }
  74934. else {
  74935. outputLiminance = _this._hdrCurrentLuminance;
  74936. }
  74937. }
  74938. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74939. effect.setFloat("averageLuminance", outputLiminance);
  74940. lastTime = time;
  74941. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74942. };
  74943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74944. };
  74945. // Create lens flare post-process
  74946. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74947. var _this = this;
  74948. 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);
  74949. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74950. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74951. 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);
  74952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74953. var resolution = new BABYLON.Vector2(0, 0);
  74954. // Lens flare
  74955. this.lensFlarePostProcess.onApply = function (effect) {
  74956. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74957. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74958. effect.setFloat("strength", _this.lensFlareStrength);
  74959. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74960. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74961. // Shift
  74962. resolution.x = _this.lensFlarePostProcess.width;
  74963. resolution.y = _this.lensFlarePostProcess.height;
  74964. effect.setVector2("resolution", resolution);
  74965. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74966. };
  74967. // Compose
  74968. 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);
  74969. 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);
  74970. this.lensFlareComposePostProcess.onApply = function (effect) {
  74971. if (!_this._scene.activeCamera) {
  74972. return;
  74973. }
  74974. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74975. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74976. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74977. // Lens start rotation matrix
  74978. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74979. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74980. 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));
  74981. camRot *= 4.0;
  74982. 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);
  74983. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74984. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74985. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74986. };
  74987. };
  74988. // Create depth-of-field post-process
  74989. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74990. var _this = this;
  74991. 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);
  74992. this.depthOfFieldPostProcess.onApply = function (effect) {
  74993. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74994. effect.setTexture("depthSampler", _this._getDepthTexture());
  74995. effect.setFloat("distance", _this.depthOfFieldDistance);
  74996. };
  74997. // Add to pipeline
  74998. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74999. };
  75000. // Create motion blur post-process
  75001. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75002. var _this = this;
  75003. 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);
  75004. var motionScale = 0;
  75005. var prevViewProjection = BABYLON.Matrix.Identity();
  75006. var invViewProjection = BABYLON.Matrix.Identity();
  75007. var viewProjection = BABYLON.Matrix.Identity();
  75008. var screenSize = BABYLON.Vector2.Zero();
  75009. this.motionBlurPostProcess.onApply = function (effect) {
  75010. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75011. viewProjection.invertToRef(invViewProjection);
  75012. effect.setMatrix("inverseViewProjection", invViewProjection);
  75013. effect.setMatrix("prevViewProjection", prevViewProjection);
  75014. prevViewProjection = viewProjection;
  75015. screenSize.x = _this.motionBlurPostProcess.width;
  75016. screenSize.y = _this.motionBlurPostProcess.height;
  75017. effect.setVector2("screenSize", screenSize);
  75018. motionScale = scene.getEngine().getFps() / 60.0;
  75019. effect.setFloat("motionScale", motionScale);
  75020. effect.setFloat("motionStrength", _this.motionStrength);
  75021. effect.setTexture("depthSampler", _this._getDepthTexture());
  75022. };
  75023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75024. };
  75025. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75026. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75027. var renderer = this._scene.enableGeometryBufferRenderer();
  75028. return renderer.getGBuffer().textures[0];
  75029. }
  75030. return this._scene.enableDepthRenderer().getDepthMap();
  75031. };
  75032. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75033. for (var i = 0; i < this._cameras.length; i++) {
  75034. var camera = this._cameras[i];
  75035. if (this.originalPostProcess) {
  75036. this.originalPostProcess.dispose(camera);
  75037. }
  75038. if (this.downSampleX4PostProcess) {
  75039. this.downSampleX4PostProcess.dispose(camera);
  75040. }
  75041. if (this.brightPassPostProcess) {
  75042. this.brightPassPostProcess.dispose(camera);
  75043. }
  75044. if (this.textureAdderPostProcess) {
  75045. this.textureAdderPostProcess.dispose(camera);
  75046. }
  75047. if (this.textureAdderFinalPostProcess) {
  75048. this.textureAdderFinalPostProcess.dispose(camera);
  75049. }
  75050. if (this.volumetricLightPostProcess) {
  75051. this.volumetricLightPostProcess.dispose(camera);
  75052. }
  75053. if (this.volumetricLightSmoothXPostProcess) {
  75054. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75055. }
  75056. if (this.volumetricLightSmoothYPostProcess) {
  75057. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75058. }
  75059. if (this.volumetricLightMergePostProces) {
  75060. this.volumetricLightMergePostProces.dispose(camera);
  75061. }
  75062. if (this.volumetricLightFinalPostProcess) {
  75063. this.volumetricLightFinalPostProcess.dispose(camera);
  75064. }
  75065. if (this.lensFlarePostProcess) {
  75066. this.lensFlarePostProcess.dispose(camera);
  75067. }
  75068. if (this.lensFlareComposePostProcess) {
  75069. this.lensFlareComposePostProcess.dispose(camera);
  75070. }
  75071. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75072. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75073. }
  75074. if (this.luminancePostProcess) {
  75075. this.luminancePostProcess.dispose(camera);
  75076. }
  75077. if (this.hdrPostProcess) {
  75078. this.hdrPostProcess.dispose(camera);
  75079. }
  75080. if (this.hdrFinalPostProcess) {
  75081. this.hdrFinalPostProcess.dispose(camera);
  75082. }
  75083. if (this.depthOfFieldPostProcess) {
  75084. this.depthOfFieldPostProcess.dispose(camera);
  75085. }
  75086. if (this.motionBlurPostProcess) {
  75087. this.motionBlurPostProcess.dispose(camera);
  75088. }
  75089. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75090. this.blurHPostProcesses[j].dispose(camera);
  75091. }
  75092. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75093. this.blurVPostProcesses[j].dispose(camera);
  75094. }
  75095. }
  75096. this.originalPostProcess = null;
  75097. this.downSampleX4PostProcess = null;
  75098. this.brightPassPostProcess = null;
  75099. this.textureAdderPostProcess = null;
  75100. this.textureAdderFinalPostProcess = null;
  75101. this.volumetricLightPostProcess = null;
  75102. this.volumetricLightSmoothXPostProcess = null;
  75103. this.volumetricLightSmoothYPostProcess = null;
  75104. this.volumetricLightMergePostProces = null;
  75105. this.volumetricLightFinalPostProcess = null;
  75106. this.lensFlarePostProcess = null;
  75107. this.lensFlareComposePostProcess = null;
  75108. this.luminancePostProcess = null;
  75109. this.hdrPostProcess = null;
  75110. this.hdrFinalPostProcess = null;
  75111. this.depthOfFieldPostProcess = null;
  75112. this.motionBlurPostProcess = null;
  75113. this.luminanceDownSamplePostProcesses = [];
  75114. this.blurHPostProcesses = [];
  75115. this.blurVPostProcesses = [];
  75116. };
  75117. /**
  75118. * Dispose of the pipeline and stop all post processes
  75119. */
  75120. StandardRenderingPipeline.prototype.dispose = function () {
  75121. this._disposePostProcesses();
  75122. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75123. _super.prototype.dispose.call(this);
  75124. };
  75125. /**
  75126. * Serialize the rendering pipeline (Used when exporting)
  75127. * @returns the serialized object
  75128. */
  75129. StandardRenderingPipeline.prototype.serialize = function () {
  75130. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75131. if (this.sourceLight) {
  75132. serializationObject.sourceLightId = this.sourceLight.id;
  75133. }
  75134. serializationObject.customType = "StandardRenderingPipeline";
  75135. return serializationObject;
  75136. };
  75137. /**
  75138. * Parse the serialized pipeline
  75139. * @param source Source pipeline.
  75140. * @param scene The scene to load the pipeline to.
  75141. * @param rootUrl The URL of the serialized pipeline.
  75142. * @returns An instantiated pipeline from the serialized object.
  75143. */
  75144. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75145. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75146. if (source.sourceLightId) {
  75147. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75148. }
  75149. return p;
  75150. };
  75151. // Luminance steps
  75152. StandardRenderingPipeline.LuminanceSteps = 6;
  75153. __decorate([
  75154. BABYLON.serialize()
  75155. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75156. __decorate([
  75157. BABYLON.serialize()
  75158. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75159. __decorate([
  75160. BABYLON.serialize()
  75161. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75162. __decorate([
  75163. BABYLON.serialize()
  75164. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75165. __decorate([
  75166. BABYLON.serializeAsTexture("lensTexture")
  75167. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75168. __decorate([
  75169. BABYLON.serialize()
  75170. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75171. __decorate([
  75172. BABYLON.serialize()
  75173. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75174. __decorate([
  75175. BABYLON.serialize()
  75176. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75177. __decorate([
  75178. BABYLON.serialize()
  75179. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75180. __decorate([
  75181. BABYLON.serialize()
  75182. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75183. __decorate([
  75184. BABYLON.serialize()
  75185. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75186. __decorate([
  75187. BABYLON.serializeAsTexture("lensColorTexture")
  75188. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75189. __decorate([
  75190. BABYLON.serialize()
  75191. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75192. __decorate([
  75193. BABYLON.serialize()
  75194. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75195. __decorate([
  75196. BABYLON.serialize()
  75197. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75201. __decorate([
  75202. BABYLON.serializeAsTexture("lensStarTexture")
  75203. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75204. __decorate([
  75205. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75206. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75207. __decorate([
  75208. BABYLON.serialize()
  75209. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75210. __decorate([
  75211. BABYLON.serialize()
  75212. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75213. __decorate([
  75214. BABYLON.serialize()
  75215. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75216. __decorate([
  75217. BABYLON.serialize()
  75218. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75219. __decorate([
  75220. BABYLON.serialize()
  75221. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75222. __decorate([
  75223. BABYLON.serialize()
  75224. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75225. __decorate([
  75226. BABYLON.serialize()
  75227. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75228. __decorate([
  75229. BABYLON.serialize()
  75230. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75231. __decorate([
  75232. BABYLON.serialize()
  75233. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75234. __decorate([
  75235. BABYLON.serialize()
  75236. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75237. __decorate([
  75238. BABYLON.serialize()
  75239. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75240. __decorate([
  75241. BABYLON.serialize()
  75242. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75243. return StandardRenderingPipeline;
  75244. }(BABYLON.PostProcessRenderPipeline));
  75245. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75246. })(BABYLON || (BABYLON = {}));
  75247. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75248. var BABYLON;
  75249. (function (BABYLON) {
  75250. var FxaaPostProcess = /** @class */ (function (_super) {
  75251. __extends(FxaaPostProcess, _super);
  75252. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75253. if (camera === void 0) { camera = null; }
  75254. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75255. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75256. var defines = _this._getDefines();
  75257. _this.updateEffect(defines);
  75258. _this.onApplyObservable.add(function (effect) {
  75259. var texelSize = _this.texelSize;
  75260. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75261. });
  75262. return _this;
  75263. }
  75264. FxaaPostProcess.prototype._getDefines = function () {
  75265. var engine = this.getEngine();
  75266. if (!engine) {
  75267. return null;
  75268. }
  75269. var glInfo = engine.getGlInfo();
  75270. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75271. return "#define MALI 1\n";
  75272. }
  75273. return null;
  75274. };
  75275. return FxaaPostProcess;
  75276. }(BABYLON.PostProcess));
  75277. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75278. })(BABYLON || (BABYLON = {}));
  75279. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75280. var BABYLON;
  75281. (function (BABYLON) {
  75282. /**
  75283. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75284. */
  75285. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75286. __extends(ChromaticAberrationPostProcess, _super);
  75287. /**
  75288. * Creates a new instance ChromaticAberrationPostProcess
  75289. * @param name The name of the effect.
  75290. * @param screenWidth The width of the screen to apply the effect on.
  75291. * @param screenHeight The height of the screen to apply the effect on.
  75292. * @param options The required width/height ratio to downsize to before computing the render pass.
  75293. * @param camera The camera to apply the render pass to.
  75294. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75295. * @param engine The engine which the post process will be applied. (default: current engine)
  75296. * @param reusable If the post process can be reused on the same frame. (default: false)
  75297. * @param textureType Type of textures used when performing the post process. (default: 0)
  75298. * @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)
  75299. */
  75300. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75301. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75302. if (blockCompilation === void 0) { blockCompilation = false; }
  75303. 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;
  75304. /**
  75305. * The amount of seperation of rgb channels (default: 30)
  75306. */
  75307. _this.aberrationAmount = 30;
  75308. /**
  75309. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75310. */
  75311. _this.radialIntensity = 0;
  75312. /**
  75313. * 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))
  75314. */
  75315. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75316. /**
  75317. * 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))
  75318. */
  75319. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75320. _this.onApplyObservable.add(function (effect) {
  75321. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75322. effect.setFloat('screen_width', screenWidth);
  75323. effect.setFloat('screen_height', screenHeight);
  75324. effect.setFloat('radialIntensity', _this.radialIntensity);
  75325. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75326. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75327. });
  75328. return _this;
  75329. }
  75330. return ChromaticAberrationPostProcess;
  75331. }(BABYLON.PostProcess));
  75332. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75333. })(BABYLON || (BABYLON = {}));
  75334. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75335. var BABYLON;
  75336. (function (BABYLON) {
  75337. /**
  75338. * The GrainPostProcess adds noise to the image at mid luminance levels
  75339. */
  75340. var GrainPostProcess = /** @class */ (function (_super) {
  75341. __extends(GrainPostProcess, _super);
  75342. /**
  75343. * Creates a new instance of @see GrainPostProcess
  75344. * @param name The name of the effect.
  75345. * @param options The required width/height ratio to downsize to before computing the render pass.
  75346. * @param camera The camera to apply the render pass to.
  75347. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75348. * @param engine The engine which the post process will be applied. (default: current engine)
  75349. * @param reusable If the post process can be reused on the same frame. (default: false)
  75350. * @param textureType Type of textures used when performing the post process. (default: 0)
  75351. * @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)
  75352. */
  75353. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75354. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75355. if (blockCompilation === void 0) { blockCompilation = false; }
  75356. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75357. /**
  75358. * The intensity of the grain added (default: 30)
  75359. */
  75360. _this.intensity = 30;
  75361. /**
  75362. * If the grain should be randomized on every frame
  75363. */
  75364. _this.animated = false;
  75365. _this.onApplyObservable.add(function (effect) {
  75366. effect.setFloat('intensity', _this.intensity);
  75367. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75368. });
  75369. return _this;
  75370. }
  75371. return GrainPostProcess;
  75372. }(BABYLON.PostProcess));
  75373. BABYLON.GrainPostProcess = GrainPostProcess;
  75374. })(BABYLON || (BABYLON = {}));
  75375. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75376. var BABYLON;
  75377. (function (BABYLON) {
  75378. /**
  75379. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75380. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75381. */
  75382. var SharpenPostProcess = /** @class */ (function (_super) {
  75383. __extends(SharpenPostProcess, _super);
  75384. /**
  75385. * Creates a new instance ConvolutionPostProcess
  75386. * @param name The name of the effect.
  75387. * @param options The required width/height ratio to downsize to before computing the render pass.
  75388. * @param camera The camera to apply the render pass to.
  75389. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75390. * @param engine The engine which the post process will be applied. (default: current engine)
  75391. * @param reusable If the post process can be reused on the same frame. (default: false)
  75392. * @param textureType Type of textures used when performing the post process. (default: 0)
  75393. * @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)
  75394. */
  75395. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75396. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75397. if (blockCompilation === void 0) { blockCompilation = false; }
  75398. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75399. /**
  75400. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75401. */
  75402. _this.colorAmount = 1.0;
  75403. /**
  75404. * How much sharpness should be applied (default: 0.3)
  75405. */
  75406. _this.edgeAmount = 0.3;
  75407. _this.onApply = function (effect) {
  75408. effect.setFloat2("screenSize", _this.width, _this.height);
  75409. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75410. };
  75411. return _this;
  75412. }
  75413. return SharpenPostProcess;
  75414. }(BABYLON.PostProcess));
  75415. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75416. })(BABYLON || (BABYLON = {}));
  75417. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75418. var BABYLON;
  75419. (function (BABYLON) {
  75420. /**
  75421. * The Blur Post Process which blurs an image based on a kernel and direction.
  75422. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75423. */
  75424. var BlurPostProcess = /** @class */ (function (_super) {
  75425. __extends(BlurPostProcess, _super);
  75426. /**
  75427. * Creates a new instance BlurPostProcess
  75428. * @param name The name of the effect.
  75429. * @param direction The direction in which to blur the image.
  75430. * @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.
  75431. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75432. * @param camera The camera to apply the render pass to.
  75433. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75434. * @param engine The engine which the post process will be applied. (default: current engine)
  75435. * @param reusable If the post process can be reused on the same frame. (default: false)
  75436. * @param textureType Type of textures used when performing the post process. (default: 0)
  75437. * @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)
  75438. */
  75439. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75441. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75442. if (defines === void 0) { defines = ""; }
  75443. if (blockCompilation === void 0) { blockCompilation = false; }
  75444. 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;
  75445. _this.direction = direction;
  75446. _this.blockCompilation = blockCompilation;
  75447. _this._packedFloat = false;
  75448. _this._staticDefines = "";
  75449. _this._staticDefines = defines;
  75450. _this.onApplyObservable.add(function (effect) {
  75451. if (_this._outputTexture) {
  75452. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75453. }
  75454. else {
  75455. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75456. }
  75457. });
  75458. _this.kernel = kernel;
  75459. return _this;
  75460. }
  75461. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75462. /**
  75463. * Gets the length in pixels of the blur sample region
  75464. */
  75465. get: function () {
  75466. return this._idealKernel;
  75467. },
  75468. /**
  75469. * Sets the length in pixels of the blur sample region
  75470. */
  75471. set: function (v) {
  75472. if (this._idealKernel === v) {
  75473. return;
  75474. }
  75475. v = Math.max(v, 1);
  75476. this._idealKernel = v;
  75477. this._kernel = this._nearestBestKernel(v);
  75478. if (!this.blockCompilation) {
  75479. this._updateParameters();
  75480. }
  75481. },
  75482. enumerable: true,
  75483. configurable: true
  75484. });
  75485. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75486. /**
  75487. * Gets wether or not the blur is unpacking/repacking floats
  75488. */
  75489. get: function () {
  75490. return this._packedFloat;
  75491. },
  75492. /**
  75493. * Sets wether or not the blur needs to unpack/repack floats
  75494. */
  75495. set: function (v) {
  75496. if (this._packedFloat === v) {
  75497. return;
  75498. }
  75499. this._packedFloat = v;
  75500. if (!this.blockCompilation) {
  75501. this._updateParameters();
  75502. }
  75503. },
  75504. enumerable: true,
  75505. configurable: true
  75506. });
  75507. /**
  75508. * Updates the effect with the current post process compile time values and recompiles the shader.
  75509. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75510. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75511. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75512. * @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
  75513. * @param onCompiled Called when the shader has been compiled.
  75514. * @param onError Called if there is an error when compiling a shader.
  75515. */
  75516. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75517. if (defines === void 0) { defines = null; }
  75518. if (uniforms === void 0) { uniforms = null; }
  75519. if (samplers === void 0) { samplers = null; }
  75520. this._updateParameters(onCompiled, onError);
  75521. };
  75522. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75523. // Generate sampling offsets and weights
  75524. var N = this._kernel;
  75525. var centerIndex = (N - 1) / 2;
  75526. // Generate Gaussian sampling weights over kernel
  75527. var offsets = [];
  75528. var weights = [];
  75529. var totalWeight = 0;
  75530. for (var i = 0; i < N; i++) {
  75531. var u = i / (N - 1);
  75532. var w = this._gaussianWeight(u * 2.0 - 1);
  75533. offsets[i] = (i - centerIndex);
  75534. weights[i] = w;
  75535. totalWeight += w;
  75536. }
  75537. // Normalize weights
  75538. for (var i = 0; i < weights.length; i++) {
  75539. weights[i] /= totalWeight;
  75540. }
  75541. // Optimize: combine samples to take advantage of hardware linear sampling
  75542. // Walk from left to center, combining pairs (symmetrically)
  75543. var linearSamplingWeights = [];
  75544. var linearSamplingOffsets = [];
  75545. var linearSamplingMap = [];
  75546. for (var i = 0; i <= centerIndex; i += 2) {
  75547. var j = Math.min(i + 1, Math.floor(centerIndex));
  75548. var singleCenterSample = i === j;
  75549. if (singleCenterSample) {
  75550. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75551. }
  75552. else {
  75553. var sharedCell = j === centerIndex;
  75554. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75555. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75556. if (offsetLinear === 0) {
  75557. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75558. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75559. }
  75560. else {
  75561. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75562. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75563. }
  75564. }
  75565. }
  75566. for (var i = 0; i < linearSamplingMap.length; i++) {
  75567. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75568. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75569. }
  75570. // Replace with optimized
  75571. offsets = linearSamplingOffsets;
  75572. weights = linearSamplingWeights;
  75573. // Generate shaders
  75574. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75575. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75576. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75577. var defines = "";
  75578. defines += this._staticDefines;
  75579. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75580. if (this._staticDefines.indexOf("DOF") != -1) {
  75581. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75582. varyingCount--;
  75583. }
  75584. for (var i = 0; i < varyingCount; i++) {
  75585. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75586. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75587. }
  75588. var depCount = 0;
  75589. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75590. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75591. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75592. depCount++;
  75593. }
  75594. if (this.packedFloat) {
  75595. defines += "#define PACKEDFLOAT 1";
  75596. }
  75597. this.blockCompilation = false;
  75598. _super.prototype.updateEffect.call(this, defines, null, null, {
  75599. varyingCount: varyingCount,
  75600. depCount: depCount
  75601. }, onCompiled, onError);
  75602. };
  75603. /**
  75604. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75605. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75606. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75607. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75608. * The gaps between physical kernels are compensated for in the weighting of the samples
  75609. * @param idealKernel Ideal blur kernel.
  75610. * @return Nearest best kernel.
  75611. */
  75612. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75613. var v = Math.round(idealKernel);
  75614. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75615. var k = _a[_i];
  75616. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75617. return Math.max(k, 3);
  75618. }
  75619. }
  75620. return Math.max(v, 3);
  75621. };
  75622. /**
  75623. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75624. * @param x The point on the Gaussian distribution to sample.
  75625. * @return the value of the Gaussian function at x.
  75626. */
  75627. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75628. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75629. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75630. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75631. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75632. // truncated at around 1.3% of peak strength.
  75633. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75634. var sigma = (1 / 3);
  75635. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75636. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75637. var weight = (1.0 / denominator) * Math.exp(exponent);
  75638. return weight;
  75639. };
  75640. /**
  75641. * Generates a string that can be used as a floating point number in GLSL.
  75642. * @param x Value to print.
  75643. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75644. * @return GLSL float string.
  75645. */
  75646. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75647. if (decimalFigures === void 0) { decimalFigures = 8; }
  75648. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75649. };
  75650. return BlurPostProcess;
  75651. }(BABYLON.PostProcess));
  75652. BABYLON.BlurPostProcess = BlurPostProcess;
  75653. })(BABYLON || (BABYLON = {}));
  75654. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75655. var BABYLON;
  75656. (function (BABYLON) {
  75657. /**
  75658. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75659. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75660. * based on samples that have a large difference in distance than the center pixel.
  75661. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75662. */
  75663. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75664. __extends(DepthOfFieldBlurPostProcess, _super);
  75665. /**
  75666. * Creates a new instance CircleOfConfusionPostProcess
  75667. * @param name The name of the effect.
  75668. * @param scene The scene the effect belongs to.
  75669. * @param direction The direction the blur should be applied.
  75670. * @param kernel The size of the kernel used to blur.
  75671. * @param options The required width/height ratio to downsize to before computing the render pass.
  75672. * @param camera The camera to apply the render pass to.
  75673. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75674. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75675. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75676. * @param engine The engine which the post process will be applied. (default: current engine)
  75677. * @param reusable If the post process can be reused on the same frame. (default: false)
  75678. * @param textureType Type of textures used when performing the post process. (default: 0)
  75679. * @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)
  75680. */
  75681. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75682. if (imageToBlur === void 0) { imageToBlur = null; }
  75683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75684. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75685. if (blockCompilation === void 0) { blockCompilation = false; }
  75686. 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;
  75687. _this.direction = direction;
  75688. _this.onApplyObservable.add(function (effect) {
  75689. if (imageToBlur != null) {
  75690. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75691. }
  75692. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75693. if (scene.activeCamera) {
  75694. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75695. }
  75696. });
  75697. return _this;
  75698. }
  75699. return DepthOfFieldBlurPostProcess;
  75700. }(BABYLON.BlurPostProcess));
  75701. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75702. })(BABYLON || (BABYLON = {}));
  75703. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75704. var BABYLON;
  75705. (function (BABYLON) {
  75706. /**
  75707. * Options to be set when merging outputs from the default pipeline.
  75708. */
  75709. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75710. function DepthOfFieldMergePostProcessOptions() {
  75711. }
  75712. return DepthOfFieldMergePostProcessOptions;
  75713. }());
  75714. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75715. /**
  75716. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75717. */
  75718. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75719. __extends(DepthOfFieldMergePostProcess, _super);
  75720. /**
  75721. * Creates a new instance of DepthOfFieldMergePostProcess
  75722. * @param name The name of the effect.
  75723. * @param originalFromInput Post process which's input will be used for the merge.
  75724. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75725. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75726. * @param options The required width/height ratio to downsize to before computing the render pass.
  75727. * @param camera The camera to apply the render pass to.
  75728. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75729. * @param engine The engine which the post process will be applied. (default: current engine)
  75730. * @param reusable If the post process can be reused on the same frame. (default: false)
  75731. * @param textureType Type of textures used when performing the post process. (default: 0)
  75732. * @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)
  75733. */
  75734. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75735. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75736. if (blockCompilation === void 0) { blockCompilation = false; }
  75737. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75738. _this.blurSteps = blurSteps;
  75739. _this.onApplyObservable.add(function (effect) {
  75740. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75741. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75742. blurSteps.forEach(function (step, index) {
  75743. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75744. });
  75745. });
  75746. if (!blockCompilation) {
  75747. _this.updateEffect();
  75748. }
  75749. return _this;
  75750. }
  75751. /**
  75752. * Updates the effect with the current post process compile time values and recompiles the shader.
  75753. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75754. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75755. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75756. * @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
  75757. * @param onCompiled Called when the shader has been compiled.
  75758. * @param onError Called if there is an error when compiling a shader.
  75759. */
  75760. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75761. if (defines === void 0) { defines = null; }
  75762. if (uniforms === void 0) { uniforms = null; }
  75763. if (samplers === void 0) { samplers = null; }
  75764. if (!defines) {
  75765. defines = "";
  75766. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75767. }
  75768. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75769. };
  75770. return DepthOfFieldMergePostProcess;
  75771. }(BABYLON.PostProcess));
  75772. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75773. })(BABYLON || (BABYLON = {}));
  75774. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75775. var BABYLON;
  75776. (function (BABYLON) {
  75777. /**
  75778. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75779. */
  75780. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75781. __extends(CircleOfConfusionPostProcess, _super);
  75782. /**
  75783. * Creates a new instance CircleOfConfusionPostProcess
  75784. * @param name The name of the effect.
  75785. * @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.
  75786. * @param options The required width/height ratio to downsize to before computing the render pass.
  75787. * @param camera The camera to apply the render pass to.
  75788. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75789. * @param engine The engine which the post process will be applied. (default: current engine)
  75790. * @param reusable If the post process can be reused on the same frame. (default: false)
  75791. * @param textureType Type of textures used when performing the post process. (default: 0)
  75792. * @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)
  75793. */
  75794. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75795. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75796. if (blockCompilation === void 0) { blockCompilation = false; }
  75797. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75798. /**
  75799. * 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.
  75800. */
  75801. _this.lensSize = 50;
  75802. /**
  75803. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75804. */
  75805. _this.fStop = 1.4;
  75806. /**
  75807. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75808. */
  75809. _this.focusDistance = 2000;
  75810. /**
  75811. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75812. */
  75813. _this.focalLength = 50;
  75814. _this._depthTexture = null;
  75815. _this._depthTexture = depthTexture;
  75816. _this.onApplyObservable.add(function (effect) {
  75817. if (!_this._depthTexture) {
  75818. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75819. return;
  75820. }
  75821. effect.setTexture("depthSampler", _this._depthTexture);
  75822. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75823. var aperture = _this.lensSize / _this.fStop;
  75824. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75825. effect.setFloat('focusDistance', _this.focusDistance);
  75826. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75827. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75828. });
  75829. return _this;
  75830. }
  75831. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75832. /**
  75833. * 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.
  75834. */
  75835. set: function (value) {
  75836. this._depthTexture = value;
  75837. },
  75838. enumerable: true,
  75839. configurable: true
  75840. });
  75841. return CircleOfConfusionPostProcess;
  75842. }(BABYLON.PostProcess));
  75843. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75844. })(BABYLON || (BABYLON = {}));
  75845. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75846. var BABYLON;
  75847. (function (BABYLON) {
  75848. /**
  75849. * Specifies the level of max blur that should be applied when using the depth of field effect
  75850. */
  75851. var DepthOfFieldEffectBlurLevel;
  75852. (function (DepthOfFieldEffectBlurLevel) {
  75853. /**
  75854. * Subtle blur
  75855. */
  75856. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75857. /**
  75858. * Medium blur
  75859. */
  75860. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75861. /**
  75862. * Large blur
  75863. */
  75864. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75865. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75866. ;
  75867. /**
  75868. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75869. */
  75870. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75871. __extends(DepthOfFieldEffect, _super);
  75872. /**
  75873. * Creates a new instance DepthOfFieldEffect
  75874. * @param scene The scene the effect belongs to.
  75875. * @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.
  75876. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75877. * @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)
  75878. */
  75879. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75880. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75881. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75882. if (blockCompilation === void 0) { blockCompilation = false; }
  75883. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75884. return _this._effects;
  75885. }, true) || this;
  75886. /**
  75887. * Internal post processes in depth of field effect
  75888. */
  75889. _this._effects = [];
  75890. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75891. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75892. // 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)
  75893. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75894. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75895. _this._depthOfFieldBlurY = [];
  75896. _this._depthOfFieldBlurX = [];
  75897. var blurCount = 1;
  75898. var kernelSize = 15;
  75899. switch (blurLevel) {
  75900. case DepthOfFieldEffectBlurLevel.High: {
  75901. blurCount = 3;
  75902. kernelSize = 51;
  75903. break;
  75904. }
  75905. case DepthOfFieldEffectBlurLevel.Medium: {
  75906. blurCount = 2;
  75907. kernelSize = 31;
  75908. break;
  75909. }
  75910. default: {
  75911. kernelSize = 15;
  75912. blurCount = 1;
  75913. break;
  75914. }
  75915. }
  75916. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75917. var ratio = 1.0;
  75918. for (var i = 0; i < blurCount; i++) {
  75919. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75920. blurY.autoClear = false;
  75921. ratio = 0.75 / Math.pow(2, i);
  75922. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75923. blurX.autoClear = false;
  75924. _this._depthOfFieldBlurY.push(blurY);
  75925. _this._depthOfFieldBlurX.push(blurX);
  75926. }
  75927. // Set all post processes on the effect.
  75928. _this._effects = [_this._circleOfConfusion];
  75929. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75930. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75931. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75932. }
  75933. // Merge blurred images with original image based on circleOfConfusion
  75934. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75935. _this._dofMerge.autoClear = false;
  75936. _this._effects.push(_this._dofMerge);
  75937. return _this;
  75938. }
  75939. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75940. get: function () {
  75941. return this._circleOfConfusion.focalLength;
  75942. },
  75943. /**
  75944. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75945. */
  75946. set: function (value) {
  75947. this._circleOfConfusion.focalLength = value;
  75948. },
  75949. enumerable: true,
  75950. configurable: true
  75951. });
  75952. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75953. get: function () {
  75954. return this._circleOfConfusion.fStop;
  75955. },
  75956. /**
  75957. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75958. */
  75959. set: function (value) {
  75960. this._circleOfConfusion.fStop = value;
  75961. },
  75962. enumerable: true,
  75963. configurable: true
  75964. });
  75965. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75966. get: function () {
  75967. return this._circleOfConfusion.focusDistance;
  75968. },
  75969. /**
  75970. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75971. */
  75972. set: function (value) {
  75973. this._circleOfConfusion.focusDistance = value;
  75974. },
  75975. enumerable: true,
  75976. configurable: true
  75977. });
  75978. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75979. get: function () {
  75980. return this._circleOfConfusion.lensSize;
  75981. },
  75982. /**
  75983. * 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.
  75984. */
  75985. set: function (value) {
  75986. this._circleOfConfusion.lensSize = value;
  75987. },
  75988. enumerable: true,
  75989. configurable: true
  75990. });
  75991. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75992. /**
  75993. * 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.
  75994. */
  75995. set: function (value) {
  75996. this._circleOfConfusion.depthTexture = value;
  75997. },
  75998. enumerable: true,
  75999. configurable: true
  76000. });
  76001. /**
  76002. * Disposes each of the internal effects for a given camera.
  76003. * @param camera The camera to dispose the effect on.
  76004. */
  76005. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76006. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76007. this._effects[effectIndex].dispose(camera);
  76008. }
  76009. };
  76010. /**
  76011. * Internal
  76012. */
  76013. DepthOfFieldEffect.prototype._updateEffects = function () {
  76014. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76015. this._effects[effectIndex].updateEffect();
  76016. }
  76017. };
  76018. /**
  76019. * Internal
  76020. * @returns if all the contained post processes are ready.
  76021. */
  76022. DepthOfFieldEffect.prototype._isReady = function () {
  76023. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76024. if (!this._effects[effectIndex].isReady()) {
  76025. return false;
  76026. }
  76027. }
  76028. return true;
  76029. };
  76030. return DepthOfFieldEffect;
  76031. }(BABYLON.PostProcessRenderEffect));
  76032. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76033. })(BABYLON || (BABYLON = {}));
  76034. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76035. var BABYLON;
  76036. (function (BABYLON) {
  76037. /**
  76038. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76039. */
  76040. var BloomMergePostProcess = /** @class */ (function (_super) {
  76041. __extends(BloomMergePostProcess, _super);
  76042. /**
  76043. * Creates a new instance of @see BloomMergePostProcess
  76044. * @param name The name of the effect.
  76045. * @param originalFromInput Post process which's input will be used for the merge.
  76046. * @param blurred Blurred highlights post process which's output will be used.
  76047. * @param weight Weight of the bloom to be added to the original input.
  76048. * @param options The required width/height ratio to downsize to before computing the render pass.
  76049. * @param camera The camera to apply the render pass to.
  76050. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76051. * @param engine The engine which the post process will be applied. (default: current engine)
  76052. * @param reusable If the post process can be reused on the same frame. (default: false)
  76053. * @param textureType Type of textures used when performing the post process. (default: 0)
  76054. * @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)
  76055. */
  76056. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76057. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76058. if (blockCompilation === void 0) { blockCompilation = false; }
  76059. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76060. _this.weight = weight;
  76061. _this.onApplyObservable.add(function (effect) {
  76062. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76063. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76064. effect.setFloat("bloomWeight", _this.weight);
  76065. });
  76066. if (!blockCompilation) {
  76067. _this.updateEffect();
  76068. }
  76069. return _this;
  76070. }
  76071. return BloomMergePostProcess;
  76072. }(BABYLON.PostProcess));
  76073. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76074. })(BABYLON || (BABYLON = {}));
  76075. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76076. var BABYLON;
  76077. (function (BABYLON) {
  76078. /**
  76079. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  76080. */
  76081. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76082. __extends(ExtractHighlightsPostProcess, _super);
  76083. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76084. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76085. if (blockCompilation === void 0) { blockCompilation = false; }
  76086. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76087. /**
  76088. * The luminance threshold, pixels below this value will be set to black.
  76089. */
  76090. _this.threshold = 0.9;
  76091. /**
  76092. * Internal
  76093. */
  76094. _this._exposure = 1;
  76095. /**
  76096. * Post process which has the input texture to be used when performing highlight extraction
  76097. */
  76098. _this._inputPostProcess = null;
  76099. _this.onApplyObservable.add(function (effect) {
  76100. if (_this._inputPostProcess) {
  76101. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76102. }
  76103. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76104. effect.setFloat('exposure', _this._exposure);
  76105. });
  76106. return _this;
  76107. }
  76108. return ExtractHighlightsPostProcess;
  76109. }(BABYLON.PostProcess));
  76110. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76111. })(BABYLON || (BABYLON = {}));
  76112. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76113. var BABYLON;
  76114. (function (BABYLON) {
  76115. /**
  76116. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76117. */
  76118. var BloomEffect = /** @class */ (function (_super) {
  76119. __extends(BloomEffect, _super);
  76120. /**
  76121. * Creates a new instance of @see BloomEffect
  76122. * @param scene The scene the effect belongs to.
  76123. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76124. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76125. * @param bloomWeight The the strength of bloom.
  76126. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76127. * @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)
  76128. */
  76129. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76130. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76131. if (blockCompilation === void 0) { blockCompilation = false; }
  76132. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76133. return _this._effects;
  76134. }, true) || this;
  76135. _this.bloomScale = bloomScale;
  76136. /**
  76137. * Internal
  76138. */
  76139. _this._effects = [];
  76140. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76141. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  76142. _this._blurX.alwaysForcePOT = true;
  76143. _this._blurX.autoClear = false;
  76144. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  76145. _this._blurY.alwaysForcePOT = true;
  76146. _this._blurY.autoClear = false;
  76147. _this.kernel = bloomKernel;
  76148. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76149. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76150. _this._merge.autoClear = false;
  76151. _this._effects.push(_this._merge);
  76152. return _this;
  76153. }
  76154. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76155. /**
  76156. * The luminance threshold to find bright areas of the image to bloom.
  76157. */
  76158. get: function () {
  76159. return this._downscale.threshold;
  76160. },
  76161. set: function (value) {
  76162. this._downscale.threshold = value;
  76163. },
  76164. enumerable: true,
  76165. configurable: true
  76166. });
  76167. Object.defineProperty(BloomEffect.prototype, "weight", {
  76168. /**
  76169. * The strength of the bloom.
  76170. */
  76171. get: function () {
  76172. return this._merge.weight;
  76173. },
  76174. set: function (value) {
  76175. this._merge.weight = value;
  76176. },
  76177. enumerable: true,
  76178. configurable: true
  76179. });
  76180. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76181. /**
  76182. * Specifies the size of the bloom blur kernel, relative to the final output size
  76183. */
  76184. get: function () {
  76185. return this._blurX.kernel / this.bloomScale;
  76186. },
  76187. set: function (value) {
  76188. this._blurX.kernel = value * this.bloomScale;
  76189. this._blurY.kernel = value * this.bloomScale;
  76190. },
  76191. enumerable: true,
  76192. configurable: true
  76193. });
  76194. /**
  76195. * Disposes each of the internal effects for a given camera.
  76196. * @param camera The camera to dispose the effect on.
  76197. */
  76198. BloomEffect.prototype.disposeEffects = function (camera) {
  76199. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76200. this._effects[effectIndex].dispose(camera);
  76201. }
  76202. };
  76203. /**
  76204. * Internal
  76205. */
  76206. BloomEffect.prototype._updateEffects = function () {
  76207. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76208. this._effects[effectIndex].updateEffect();
  76209. }
  76210. };
  76211. /**
  76212. * Internal
  76213. * @returns if all the contained post processes are ready.
  76214. */
  76215. BloomEffect.prototype._isReady = function () {
  76216. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76217. if (!this._effects[effectIndex].isReady()) {
  76218. return false;
  76219. }
  76220. }
  76221. return true;
  76222. };
  76223. return BloomEffect;
  76224. }(BABYLON.PostProcessRenderEffect));
  76225. BABYLON.BloomEffect = BloomEffect;
  76226. })(BABYLON || (BABYLON = {}));
  76227. //# sourceMappingURL=babylon.bloomEffect.js.map
  76228. var BABYLON;
  76229. (function (BABYLON) {
  76230. /**
  76231. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76232. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76233. */
  76234. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76235. __extends(DefaultRenderingPipeline, _super);
  76236. /**
  76237. * @constructor
  76238. * @param {string} name - The rendering pipeline name (default: "")
  76239. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76240. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76241. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76242. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76243. */
  76244. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76245. if (name === void 0) { name = ""; }
  76246. if (hdr === void 0) { hdr = true; }
  76247. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76248. if (automaticBuild === void 0) { automaticBuild = true; }
  76249. var _this = _super.call(this, scene.getEngine(), name) || this;
  76250. _this._originalCameras = [];
  76251. /**
  76252. * ID of the sharpen post process,
  76253. */
  76254. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76255. /**
  76256. * ID of the image processing post process;
  76257. */
  76258. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76259. /**
  76260. * ID of the Fast Approximate Anti-Aliasing post process;
  76261. */
  76262. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76263. /**
  76264. * ID of the chromatic aberration post process,
  76265. */
  76266. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76267. /**
  76268. * ID of the grain post process
  76269. */
  76270. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76271. /**
  76272. * Glow post process which adds a glow to emmisive areas of the image
  76273. */
  76274. _this._glowLayer = null;
  76275. /**
  76276. * Animations which can be used to tweak settings over a period of time
  76277. */
  76278. _this.animations = [];
  76279. _this._imageProcessingConfigurationObserver = null;
  76280. // Values
  76281. _this._sharpenEnabled = false;
  76282. _this._bloomEnabled = false;
  76283. _this._depthOfFieldEnabled = false;
  76284. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76285. _this._fxaaEnabled = false;
  76286. _this._imageProcessingEnabled = true;
  76287. _this._bloomScale = 0.5;
  76288. _this._chromaticAberrationEnabled = false;
  76289. _this._grainEnabled = false;
  76290. _this._buildAllowed = true;
  76291. _this._resizeObserver = null;
  76292. _this._hardwareScaleLevel = 1.0;
  76293. _this._bloomKernel = 64;
  76294. /**
  76295. * Specifies the weight of the bloom in the final rendering
  76296. */
  76297. _this._bloomWeight = 0.15;
  76298. /**
  76299. * Specifies the luma threshold for the area that will be blurred by the bloom
  76300. */
  76301. _this._bloomThreshold = 0.9;
  76302. _this._samples = 1;
  76303. _this._hasCleared = false;
  76304. _this._prevPostProcess = null;
  76305. _this._prevPrevPostProcess = null;
  76306. _this._cameras = cameras || scene.cameras;
  76307. _this._originalCameras = _this._cameras.slice();
  76308. _this._buildAllowed = automaticBuild;
  76309. // Initialize
  76310. _this._scene = scene;
  76311. var caps = _this._scene.getEngine().getCaps();
  76312. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76313. // Misc
  76314. if (_this._hdr) {
  76315. if (caps.textureHalfFloatRender) {
  76316. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76317. }
  76318. else if (caps.textureFloatRender) {
  76319. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76320. }
  76321. }
  76322. else {
  76323. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76324. }
  76325. // Attach
  76326. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76327. var engine = _this._scene.getEngine();
  76328. // Create post processes before hand so they can be modified before enabled.
  76329. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76330. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76331. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76332. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76333. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76334. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76335. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76336. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76337. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76338. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76339. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76340. _this.bloomKernel = _this.bloomKernel;
  76341. });
  76342. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76343. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76344. });
  76345. _this._buildPipeline();
  76346. return _this;
  76347. }
  76348. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76349. get: function () {
  76350. return this._sharpenEnabled;
  76351. },
  76352. /**
  76353. * Enable or disable the sharpen process from the pipeline
  76354. */
  76355. set: function (enabled) {
  76356. if (this._sharpenEnabled === enabled) {
  76357. return;
  76358. }
  76359. this._sharpenEnabled = enabled;
  76360. this._buildPipeline();
  76361. },
  76362. enumerable: true,
  76363. configurable: true
  76364. });
  76365. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76366. /**
  76367. * Specifies the size of the bloom blur kernel, relative to the final output size
  76368. */
  76369. get: function () {
  76370. return this._bloomKernel;
  76371. },
  76372. set: function (value) {
  76373. this._bloomKernel = value;
  76374. this.bloom.kernel = value / this._hardwareScaleLevel;
  76375. },
  76376. enumerable: true,
  76377. configurable: true
  76378. });
  76379. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76380. get: function () {
  76381. return this._bloomWeight;
  76382. },
  76383. /**
  76384. * The strength of the bloom.
  76385. */
  76386. set: function (value) {
  76387. if (this._bloomWeight === value) {
  76388. return;
  76389. }
  76390. this.bloom.weight = value;
  76391. this._bloomWeight = value;
  76392. },
  76393. enumerable: true,
  76394. configurable: true
  76395. });
  76396. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76397. get: function () {
  76398. return this._bloomThreshold;
  76399. },
  76400. /**
  76401. * The strength of the bloom.
  76402. */
  76403. set: function (value) {
  76404. if (this._bloomThreshold === value) {
  76405. return;
  76406. }
  76407. this.bloom.threshold = value;
  76408. this._bloomThreshold = value;
  76409. },
  76410. enumerable: true,
  76411. configurable: true
  76412. });
  76413. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76414. get: function () {
  76415. return this._bloomScale;
  76416. },
  76417. /**
  76418. * The scale of the bloom, lower value will provide better performance.
  76419. */
  76420. set: function (value) {
  76421. if (this._bloomScale === value) {
  76422. return;
  76423. }
  76424. this._bloomScale = value;
  76425. // recreate bloom and dispose old as this setting is not dynamic
  76426. this._rebuildBloom();
  76427. this._buildPipeline();
  76428. },
  76429. enumerable: true,
  76430. configurable: true
  76431. });
  76432. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76433. get: function () {
  76434. return this._bloomEnabled;
  76435. },
  76436. /**
  76437. * Enable or disable the bloom from the pipeline
  76438. */
  76439. set: function (enabled) {
  76440. if (this._bloomEnabled === enabled) {
  76441. return;
  76442. }
  76443. this._bloomEnabled = enabled;
  76444. this._buildPipeline();
  76445. },
  76446. enumerable: true,
  76447. configurable: true
  76448. });
  76449. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76450. // recreate bloom and dispose old as this setting is not dynamic
  76451. var oldBloom = this.bloom;
  76452. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76453. this.bloom.threshold = oldBloom.threshold;
  76454. for (var i = 0; i < this._cameras.length; i++) {
  76455. oldBloom.disposeEffects(this._cameras[i]);
  76456. }
  76457. };
  76458. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76459. /**
  76460. * If the depth of field is enabled.
  76461. */
  76462. get: function () {
  76463. return this._depthOfFieldEnabled;
  76464. },
  76465. set: function (enabled) {
  76466. if (this._depthOfFieldEnabled === enabled) {
  76467. return;
  76468. }
  76469. this._depthOfFieldEnabled = enabled;
  76470. this._buildPipeline();
  76471. },
  76472. enumerable: true,
  76473. configurable: true
  76474. });
  76475. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76476. /**
  76477. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76478. */
  76479. get: function () {
  76480. return this._depthOfFieldBlurLevel;
  76481. },
  76482. set: function (value) {
  76483. if (this._depthOfFieldBlurLevel === value) {
  76484. return;
  76485. }
  76486. this._depthOfFieldBlurLevel = value;
  76487. // recreate dof and dispose old as this setting is not dynamic
  76488. var oldDof = this.depthOfField;
  76489. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76490. this.depthOfField.focalLength = oldDof.focalLength;
  76491. this.depthOfField.focusDistance = oldDof.focusDistance;
  76492. this.depthOfField.fStop = oldDof.fStop;
  76493. this.depthOfField.lensSize = oldDof.lensSize;
  76494. for (var i = 0; i < this._cameras.length; i++) {
  76495. oldDof.disposeEffects(this._cameras[i]);
  76496. }
  76497. this._buildPipeline();
  76498. },
  76499. enumerable: true,
  76500. configurable: true
  76501. });
  76502. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76503. get: function () {
  76504. return this._fxaaEnabled;
  76505. },
  76506. /**
  76507. * If the anti aliasing is enabled.
  76508. */
  76509. set: function (enabled) {
  76510. if (this._fxaaEnabled === enabled) {
  76511. return;
  76512. }
  76513. this._fxaaEnabled = enabled;
  76514. this._buildPipeline();
  76515. },
  76516. enumerable: true,
  76517. configurable: true
  76518. });
  76519. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76520. get: function () {
  76521. return this._samples;
  76522. },
  76523. /**
  76524. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76525. */
  76526. set: function (sampleCount) {
  76527. if (this._samples === sampleCount) {
  76528. return;
  76529. }
  76530. this._samples = sampleCount;
  76531. this._buildPipeline();
  76532. },
  76533. enumerable: true,
  76534. configurable: true
  76535. });
  76536. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76537. get: function () {
  76538. return this._imageProcessingEnabled;
  76539. },
  76540. /**
  76541. * If image processing is enabled.
  76542. */
  76543. set: function (enabled) {
  76544. if (this._imageProcessingEnabled === enabled) {
  76545. return;
  76546. }
  76547. this._imageProcessingEnabled = enabled;
  76548. this._buildPipeline();
  76549. },
  76550. enumerable: true,
  76551. configurable: true
  76552. });
  76553. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76554. get: function () {
  76555. return this._glowLayer == null;
  76556. },
  76557. /**
  76558. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76559. */
  76560. set: function (enabled) {
  76561. if (enabled && !this._glowLayer) {
  76562. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76563. }
  76564. else if (!enabled && this._glowLayer) {
  76565. this._glowLayer.dispose();
  76566. this._glowLayer = null;
  76567. }
  76568. },
  76569. enumerable: true,
  76570. configurable: true
  76571. });
  76572. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76573. get: function () {
  76574. return this._chromaticAberrationEnabled;
  76575. },
  76576. /**
  76577. * Enable or disable the chromaticAberration process from the pipeline
  76578. */
  76579. set: function (enabled) {
  76580. if (this._chromaticAberrationEnabled === enabled) {
  76581. return;
  76582. }
  76583. this._chromaticAberrationEnabled = enabled;
  76584. this._buildPipeline();
  76585. },
  76586. enumerable: true,
  76587. configurable: true
  76588. });
  76589. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76590. get: function () {
  76591. return this._grainEnabled;
  76592. },
  76593. /**
  76594. * Enable or disable the grain process from the pipeline
  76595. */
  76596. set: function (enabled) {
  76597. if (this._grainEnabled === enabled) {
  76598. return;
  76599. }
  76600. this._grainEnabled = enabled;
  76601. this._buildPipeline();
  76602. },
  76603. enumerable: true,
  76604. configurable: true
  76605. });
  76606. /**
  76607. * Force the compilation of the entire pipeline.
  76608. */
  76609. DefaultRenderingPipeline.prototype.prepare = function () {
  76610. var previousState = this._buildAllowed;
  76611. this._buildAllowed = true;
  76612. this._buildPipeline();
  76613. this._buildAllowed = previousState;
  76614. };
  76615. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76616. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76617. if (this._hasCleared) {
  76618. postProcess.autoClear = false;
  76619. }
  76620. else {
  76621. postProcess.autoClear = true;
  76622. this._scene.autoClear = false;
  76623. this._hasCleared = true;
  76624. }
  76625. if (!skipTextureSharing) {
  76626. if (this._prevPrevPostProcess) {
  76627. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76628. }
  76629. else {
  76630. postProcess.useOwnOutput();
  76631. }
  76632. if (this._prevPostProcess) {
  76633. this._prevPrevPostProcess = this._prevPostProcess;
  76634. }
  76635. this._prevPostProcess = postProcess;
  76636. }
  76637. };
  76638. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76639. var _this = this;
  76640. if (!this._buildAllowed) {
  76641. return;
  76642. }
  76643. this._scene.autoClear = true;
  76644. var engine = this._scene.getEngine();
  76645. this._disposePostProcesses();
  76646. if (this._cameras !== null) {
  76647. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76648. // get back cameras to be used to reattach pipeline
  76649. this._cameras = this._originalCameras.slice();
  76650. }
  76651. this._reset();
  76652. this._prevPostProcess = null;
  76653. this._prevPrevPostProcess = null;
  76654. this._hasCleared = false;
  76655. if (this.depthOfFieldEnabled) {
  76656. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76657. this.depthOfField.depthTexture = depthTexture;
  76658. if (!this.depthOfField._isReady()) {
  76659. this.depthOfField._updateEffects();
  76660. }
  76661. this.addEffect(this.depthOfField);
  76662. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76663. }
  76664. if (this.bloomEnabled) {
  76665. if (!this.bloom._isReady()) {
  76666. this.bloom._updateEffects();
  76667. }
  76668. this.addEffect(this.bloom);
  76669. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76670. }
  76671. if (this._imageProcessingEnabled) {
  76672. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76673. if (this._hdr) {
  76674. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76675. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76676. }
  76677. else {
  76678. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76679. }
  76680. }
  76681. if (this.sharpenEnabled) {
  76682. if (!this.sharpen.isReady()) {
  76683. this.sharpen.updateEffect();
  76684. }
  76685. this.addEffect(this._sharpenEffect);
  76686. this._setAutoClearAndTextureSharing(this.sharpen);
  76687. }
  76688. if (this.grainEnabled) {
  76689. if (!this.grain.isReady()) {
  76690. this.grain.updateEffect();
  76691. }
  76692. this.addEffect(this._grainEffect);
  76693. this._setAutoClearAndTextureSharing(this.grain);
  76694. }
  76695. if (this.chromaticAberrationEnabled) {
  76696. if (!this.chromaticAberration.isReady()) {
  76697. this.chromaticAberration.updateEffect();
  76698. }
  76699. this.addEffect(this._chromaticAberrationEffect);
  76700. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76701. }
  76702. if (this.fxaaEnabled) {
  76703. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76704. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76705. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76706. }
  76707. if (this._cameras !== null) {
  76708. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76709. }
  76710. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76711. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76712. }
  76713. };
  76714. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76715. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76716. for (var i = 0; i < this._cameras.length; i++) {
  76717. var camera = this._cameras[i];
  76718. if (this.imageProcessing) {
  76719. this.imageProcessing.dispose(camera);
  76720. }
  76721. if (this.fxaa) {
  76722. this.fxaa.dispose(camera);
  76723. }
  76724. // These are created in the constructor and should not be disposed on every pipeline change
  76725. if (disposeNonRecreated) {
  76726. if (this.sharpen) {
  76727. this.sharpen.dispose(camera);
  76728. }
  76729. if (this.depthOfField) {
  76730. this.depthOfField.disposeEffects(camera);
  76731. }
  76732. if (this.bloom) {
  76733. this.bloom.disposeEffects(camera);
  76734. }
  76735. if (this.chromaticAberration) {
  76736. this.chromaticAberration.dispose(camera);
  76737. }
  76738. if (this.grain) {
  76739. this.grain.dispose(camera);
  76740. }
  76741. if (this._glowLayer) {
  76742. this._glowLayer.dispose();
  76743. }
  76744. }
  76745. }
  76746. this.imageProcessing = null;
  76747. this.fxaa = null;
  76748. if (disposeNonRecreated) {
  76749. this.sharpen = null;
  76750. this._sharpenEffect = null;
  76751. this.depthOfField = null;
  76752. this.bloom = null;
  76753. this.chromaticAberration = null;
  76754. this._chromaticAberrationEffect = null;
  76755. this.grain = null;
  76756. this._grainEffect = null;
  76757. this._glowLayer = null;
  76758. }
  76759. };
  76760. /**
  76761. * Dispose of the pipeline and stop all post processes
  76762. */
  76763. DefaultRenderingPipeline.prototype.dispose = function () {
  76764. this._disposePostProcesses(true);
  76765. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76766. this._scene.autoClear = true;
  76767. if (this._resizeObserver) {
  76768. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76769. this._resizeObserver = null;
  76770. }
  76771. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76772. _super.prototype.dispose.call(this);
  76773. };
  76774. /**
  76775. * Serialize the rendering pipeline (Used when exporting)
  76776. * @returns the serialized object
  76777. */
  76778. DefaultRenderingPipeline.prototype.serialize = function () {
  76779. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76780. serializationObject.customType = "DefaultRenderingPipeline";
  76781. return serializationObject;
  76782. };
  76783. /**
  76784. * Parse the serialized pipeline
  76785. * @param source Source pipeline.
  76786. * @param scene The scene to load the pipeline to.
  76787. * @param rootUrl The URL of the serialized pipeline.
  76788. * @returns An instantiated pipeline from the serialized object.
  76789. */
  76790. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76791. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76792. };
  76793. __decorate([
  76794. BABYLON.serialize()
  76795. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76796. __decorate([
  76797. BABYLON.serialize()
  76798. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76799. __decorate([
  76800. BABYLON.serialize()
  76801. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76802. __decorate([
  76803. BABYLON.serialize()
  76804. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76805. __decorate([
  76806. BABYLON.serialize()
  76807. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76808. __decorate([
  76809. BABYLON.serialize()
  76810. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76811. __decorate([
  76812. BABYLON.serialize()
  76813. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76814. __decorate([
  76815. BABYLON.serialize()
  76816. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76817. __decorate([
  76818. BABYLON.serialize()
  76819. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76820. __decorate([
  76821. BABYLON.serialize()
  76822. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76823. __decorate([
  76824. BABYLON.serialize()
  76825. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76826. __decorate([
  76827. BABYLON.serialize()
  76828. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76829. __decorate([
  76830. BABYLON.serialize()
  76831. ], DefaultRenderingPipeline.prototype, "samples", null);
  76832. __decorate([
  76833. BABYLON.serialize()
  76834. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76835. __decorate([
  76836. BABYLON.serialize()
  76837. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76838. __decorate([
  76839. BABYLON.serialize()
  76840. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76841. __decorate([
  76842. BABYLON.serialize()
  76843. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76844. return DefaultRenderingPipeline;
  76845. }(BABYLON.PostProcessRenderPipeline));
  76846. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76847. })(BABYLON || (BABYLON = {}));
  76848. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76849. var BABYLON;
  76850. (function (BABYLON) {
  76851. /**
  76852. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76853. */
  76854. var GeometryBufferRenderer = /** @class */ (function () {
  76855. /**
  76856. * Creates a new G Buffer for the scene
  76857. * @param scene The scene the buffer belongs to
  76858. * @param ratio How big is the buffer related to the main canvas.
  76859. */
  76860. function GeometryBufferRenderer(scene, ratio) {
  76861. if (ratio === void 0) { ratio = 1; }
  76862. this._enablePosition = false;
  76863. this._scene = scene;
  76864. this._ratio = ratio;
  76865. // Render target
  76866. this._createRenderTargets();
  76867. }
  76868. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76869. /**
  76870. * Set the render list (meshes to be rendered) used in the G buffer.
  76871. */
  76872. set: function (meshes) {
  76873. this._multiRenderTarget.renderList = meshes;
  76874. },
  76875. enumerable: true,
  76876. configurable: true
  76877. });
  76878. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76879. /**
  76880. * Gets wether or not G buffer are supported by the running hardware.
  76881. * This requires draw buffer supports
  76882. */
  76883. get: function () {
  76884. return this._multiRenderTarget.isSupported;
  76885. },
  76886. enumerable: true,
  76887. configurable: true
  76888. });
  76889. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76890. /**
  76891. * Gets wether or not position are enabled for the G buffer.
  76892. */
  76893. get: function () {
  76894. return this._enablePosition;
  76895. },
  76896. /**
  76897. * Sets wether or not position are enabled for the G buffer.
  76898. */
  76899. set: function (enable) {
  76900. this._enablePosition = enable;
  76901. this.dispose();
  76902. this._createRenderTargets();
  76903. },
  76904. enumerable: true,
  76905. configurable: true
  76906. });
  76907. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76908. /**
  76909. * Gets the scene associated with the buffer.
  76910. */
  76911. get: function () {
  76912. return this._scene;
  76913. },
  76914. enumerable: true,
  76915. configurable: true
  76916. });
  76917. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76918. /**
  76919. * Gets the ratio used by the buffer during its creation.
  76920. * How big is the buffer related to the main canvas.
  76921. */
  76922. get: function () {
  76923. return this._ratio;
  76924. },
  76925. enumerable: true,
  76926. configurable: true
  76927. });
  76928. /**
  76929. * Checks wether everything is ready to render a submesh to the G buffer.
  76930. * @param subMesh the submesh to check readiness for
  76931. * @param useInstances is the mesh drawn using instance or not
  76932. * @returns true if ready otherwise false
  76933. */
  76934. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76935. var material = subMesh.getMaterial();
  76936. if (material && material.disableDepthWrite) {
  76937. return false;
  76938. }
  76939. var defines = [];
  76940. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76941. var mesh = subMesh.getMesh();
  76942. // Alpha test
  76943. if (material && material.needAlphaTesting()) {
  76944. defines.push("#define ALPHATEST");
  76945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76946. attribs.push(BABYLON.VertexBuffer.UVKind);
  76947. defines.push("#define UV1");
  76948. }
  76949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76950. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76951. defines.push("#define UV2");
  76952. }
  76953. }
  76954. // Buffers
  76955. if (this._enablePosition) {
  76956. defines.push("#define POSITION");
  76957. }
  76958. // Bones
  76959. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76962. if (mesh.numBoneInfluencers > 4) {
  76963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76965. }
  76966. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76967. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76968. }
  76969. else {
  76970. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76971. }
  76972. // Instances
  76973. if (useInstances) {
  76974. defines.push("#define INSTANCES");
  76975. attribs.push("world0");
  76976. attribs.push("world1");
  76977. attribs.push("world2");
  76978. attribs.push("world3");
  76979. }
  76980. // Get correct effect
  76981. var join = defines.join("\n");
  76982. if (this._cachedDefines !== join) {
  76983. this._cachedDefines = join;
  76984. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76985. }
  76986. return this._effect.isReady();
  76987. };
  76988. /**
  76989. * Gets the current underlying G Buffer.
  76990. * @returns the buffer
  76991. */
  76992. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76993. return this._multiRenderTarget;
  76994. };
  76995. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76996. /**
  76997. * Gets the number of samples used to render the buffer (anti aliasing).
  76998. */
  76999. get: function () {
  77000. return this._multiRenderTarget.samples;
  77001. },
  77002. /**
  77003. * Sets the number of samples used to render the buffer (anti aliasing).
  77004. */
  77005. set: function (value) {
  77006. this._multiRenderTarget.samples = value;
  77007. },
  77008. enumerable: true,
  77009. configurable: true
  77010. });
  77011. /**
  77012. * Disposes the renderer and frees up associated resources.
  77013. */
  77014. GeometryBufferRenderer.prototype.dispose = function () {
  77015. this.getGBuffer().dispose();
  77016. };
  77017. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77018. var _this = this;
  77019. var engine = this._scene.getEngine();
  77020. var count = this._enablePosition ? 3 : 2;
  77021. 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 });
  77022. if (!this.isSupported) {
  77023. return;
  77024. }
  77025. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77026. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77027. this._multiRenderTarget.refreshRate = 1;
  77028. this._multiRenderTarget.renderParticles = false;
  77029. this._multiRenderTarget.renderList = null;
  77030. // set default depth value to 1.0 (far away)
  77031. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77032. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77033. });
  77034. // Custom render function
  77035. var renderSubMesh = function (subMesh) {
  77036. var mesh = subMesh.getRenderingMesh();
  77037. var scene = _this._scene;
  77038. var engine = scene.getEngine();
  77039. var material = subMesh.getMaterial();
  77040. if (!material) {
  77041. return;
  77042. }
  77043. // Culling
  77044. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77045. // Managing instances
  77046. var batch = mesh._getInstancesRenderList(subMesh._id);
  77047. if (batch.mustReturn) {
  77048. return;
  77049. }
  77050. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77051. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77052. engine.enableEffect(_this._effect);
  77053. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77054. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77055. _this._effect.setMatrix("view", scene.getViewMatrix());
  77056. // Alpha test
  77057. if (material && material.needAlphaTesting()) {
  77058. var alphaTexture = material.getAlphaTestTexture();
  77059. if (alphaTexture) {
  77060. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77061. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77062. }
  77063. }
  77064. // Bones
  77065. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77066. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77067. }
  77068. // Draw
  77069. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77070. }
  77071. };
  77072. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77073. var index;
  77074. if (depthOnlySubMeshes.length) {
  77075. engine.setColorWrite(false);
  77076. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77077. renderSubMesh(depthOnlySubMeshes.data[index]);
  77078. }
  77079. engine.setColorWrite(true);
  77080. }
  77081. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77082. renderSubMesh(opaqueSubMeshes.data[index]);
  77083. }
  77084. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77085. renderSubMesh(alphaTestSubMeshes.data[index]);
  77086. }
  77087. };
  77088. };
  77089. return GeometryBufferRenderer;
  77090. }());
  77091. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77092. })(BABYLON || (BABYLON = {}));
  77093. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77094. var BABYLON;
  77095. (function (BABYLON) {
  77096. var RefractionPostProcess = /** @class */ (function (_super) {
  77097. __extends(RefractionPostProcess, _super);
  77098. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77099. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77100. _this.color = color;
  77101. _this.depth = depth;
  77102. _this.colorLevel = colorLevel;
  77103. _this._ownRefractionTexture = true;
  77104. _this.onActivateObservable.add(function (cam) {
  77105. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77106. });
  77107. _this.onApplyObservable.add(function (effect) {
  77108. effect.setColor3("baseColor", _this.color);
  77109. effect.setFloat("depth", _this.depth);
  77110. effect.setFloat("colorLevel", _this.colorLevel);
  77111. effect.setTexture("refractionSampler", _this._refTexture);
  77112. });
  77113. return _this;
  77114. }
  77115. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77116. /**
  77117. * Gets or sets the refraction texture
  77118. * Please note that you are responsible for disposing the texture if you set it manually
  77119. */
  77120. get: function () {
  77121. return this._refTexture;
  77122. },
  77123. set: function (value) {
  77124. if (this._refTexture && this._ownRefractionTexture) {
  77125. this._refTexture.dispose();
  77126. }
  77127. this._refTexture = value;
  77128. this._ownRefractionTexture = false;
  77129. },
  77130. enumerable: true,
  77131. configurable: true
  77132. });
  77133. // Methods
  77134. RefractionPostProcess.prototype.dispose = function (camera) {
  77135. if (this._refTexture && this._ownRefractionTexture) {
  77136. this._refTexture.dispose();
  77137. this._refTexture = null;
  77138. }
  77139. _super.prototype.dispose.call(this, camera);
  77140. };
  77141. return RefractionPostProcess;
  77142. }(BABYLON.PostProcess));
  77143. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77144. })(BABYLON || (BABYLON = {}));
  77145. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77146. var BABYLON;
  77147. (function (BABYLON) {
  77148. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77149. __extends(BlackAndWhitePostProcess, _super);
  77150. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77151. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77152. _this.degree = 1;
  77153. _this.onApplyObservable.add(function (effect) {
  77154. effect.setFloat("degree", _this.degree);
  77155. });
  77156. return _this;
  77157. }
  77158. return BlackAndWhitePostProcess;
  77159. }(BABYLON.PostProcess));
  77160. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77161. })(BABYLON || (BABYLON = {}));
  77162. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77163. var BABYLON;
  77164. (function (BABYLON) {
  77165. /**
  77166. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77167. * input texture to perform effects such as edge detection or sharpening
  77168. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77169. */
  77170. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77171. __extends(ConvolutionPostProcess, _super);
  77172. /**
  77173. * Creates a new instance ConvolutionPostProcess
  77174. * @param name The name of the effect.
  77175. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77176. * @param options The required width/height ratio to downsize to before computing the render pass.
  77177. * @param camera The camera to apply the render pass to.
  77178. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77179. * @param engine The engine which the post process will be applied. (default: current engine)
  77180. * @param reusable If the post process can be reused on the same frame. (default: false)
  77181. * @param textureType Type of textures used when performing the post process. (default: 0)
  77182. */
  77183. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77184. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77185. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77186. _this.kernel = kernel;
  77187. _this.onApply = function (effect) {
  77188. effect.setFloat2("screenSize", _this.width, _this.height);
  77189. effect.setArray("kernel", _this.kernel);
  77190. };
  77191. return _this;
  77192. }
  77193. // Statics
  77194. /**
  77195. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77196. */
  77197. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77198. /**
  77199. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77200. */
  77201. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77202. /**
  77203. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77204. */
  77205. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77206. /**
  77207. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77208. */
  77209. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77210. /**
  77211. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77212. */
  77213. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77214. /**
  77215. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77216. */
  77217. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77218. return ConvolutionPostProcess;
  77219. }(BABYLON.PostProcess));
  77220. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77221. })(BABYLON || (BABYLON = {}));
  77222. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77223. var BABYLON;
  77224. (function (BABYLON) {
  77225. var FilterPostProcess = /** @class */ (function (_super) {
  77226. __extends(FilterPostProcess, _super);
  77227. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77228. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77229. _this.kernelMatrix = kernelMatrix;
  77230. _this.onApply = function (effect) {
  77231. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77232. };
  77233. return _this;
  77234. }
  77235. return FilterPostProcess;
  77236. }(BABYLON.PostProcess));
  77237. BABYLON.FilterPostProcess = FilterPostProcess;
  77238. })(BABYLON || (BABYLON = {}));
  77239. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77240. var BABYLON;
  77241. (function (BABYLON) {
  77242. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77243. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77244. __extends(VolumetricLightScatteringPostProcess, _super);
  77245. /**
  77246. * @constructor
  77247. * @param {string} name - The post-process name
  77248. * @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)
  77249. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77250. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77251. * @param {number} samples - The post-process quality, default 100
  77252. * @param {number} samplingMode - The post-process filtering mode
  77253. * @param {BABYLON.Engine} engine - The babylon engine
  77254. * @param {boolean} reusable - If the post-process is reusable
  77255. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77256. */
  77257. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77258. if (samples === void 0) { samples = 100; }
  77259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77260. 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;
  77261. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77262. /**
  77263. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77264. */
  77265. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77266. /**
  77267. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77268. */
  77269. _this.useCustomMeshPosition = false;
  77270. /**
  77271. * If the post-process should inverse the light scattering direction
  77272. */
  77273. _this.invert = true;
  77274. /**
  77275. * Array containing the excluded meshes not rendered in the internal pass
  77276. */
  77277. _this.excludedMeshes = new Array();
  77278. /**
  77279. * Controls the overall intensity of the post-process
  77280. */
  77281. _this.exposure = 0.3;
  77282. /**
  77283. * Dissipates each sample's contribution in range [0, 1]
  77284. */
  77285. _this.decay = 0.96815;
  77286. /**
  77287. * Controls the overall intensity of each sample
  77288. */
  77289. _this.weight = 0.58767;
  77290. /**
  77291. * Controls the density of each sample
  77292. */
  77293. _this.density = 0.926;
  77294. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77295. engine = scene.getEngine();
  77296. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77297. // Configure mesh
  77298. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77299. // Configure
  77300. _this._createPass(scene, ratio.passRatio || ratio);
  77301. _this.onActivate = function (camera) {
  77302. if (!_this.isSupported) {
  77303. _this.dispose(camera);
  77304. }
  77305. _this.onActivate = null;
  77306. };
  77307. _this.onApplyObservable.add(function (effect) {
  77308. _this._updateMeshScreenCoordinates(scene);
  77309. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77310. effect.setFloat("exposure", _this.exposure);
  77311. effect.setFloat("decay", _this.decay);
  77312. effect.setFloat("weight", _this.weight);
  77313. effect.setFloat("density", _this.density);
  77314. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77315. });
  77316. return _this;
  77317. }
  77318. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77319. get: function () {
  77320. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77321. return false;
  77322. },
  77323. set: function (useDiffuseColor) {
  77324. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77325. },
  77326. enumerable: true,
  77327. configurable: true
  77328. });
  77329. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77330. return "VolumetricLightScatteringPostProcess";
  77331. };
  77332. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77333. var mesh = subMesh.getMesh();
  77334. // Render this.mesh as default
  77335. if (mesh === this.mesh && mesh.material) {
  77336. return mesh.material.isReady(mesh);
  77337. }
  77338. var defines = [];
  77339. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77340. var material = subMesh.getMaterial();
  77341. // Alpha test
  77342. if (material) {
  77343. if (material.needAlphaTesting()) {
  77344. defines.push("#define ALPHATEST");
  77345. }
  77346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77347. attribs.push(BABYLON.VertexBuffer.UVKind);
  77348. defines.push("#define UV1");
  77349. }
  77350. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77352. defines.push("#define UV2");
  77353. }
  77354. }
  77355. // Bones
  77356. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77357. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77358. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77359. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77360. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77361. }
  77362. else {
  77363. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77364. }
  77365. // Instances
  77366. if (useInstances) {
  77367. defines.push("#define INSTANCES");
  77368. attribs.push("world0");
  77369. attribs.push("world1");
  77370. attribs.push("world2");
  77371. attribs.push("world3");
  77372. }
  77373. // Get correct effect
  77374. var join = defines.join("\n");
  77375. if (this._cachedDefines !== join) {
  77376. this._cachedDefines = join;
  77377. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77378. }
  77379. return this._volumetricLightScatteringPass.isReady();
  77380. };
  77381. /**
  77382. * Sets the new light position for light scattering effect
  77383. * @param {BABYLON.Vector3} The new custom light position
  77384. */
  77385. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77386. this.customMeshPosition = position;
  77387. };
  77388. /**
  77389. * Returns the light position for light scattering effect
  77390. * @return {BABYLON.Vector3} The custom light position
  77391. */
  77392. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77393. return this.customMeshPosition;
  77394. };
  77395. /**
  77396. * Disposes the internal assets and detaches the post-process from the camera
  77397. */
  77398. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77399. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77400. if (rttIndex !== -1) {
  77401. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77402. }
  77403. this._volumetricLightScatteringRTT.dispose();
  77404. _super.prototype.dispose.call(this, camera);
  77405. };
  77406. /**
  77407. * Returns the render target texture used by the post-process
  77408. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77409. */
  77410. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77411. return this._volumetricLightScatteringRTT;
  77412. };
  77413. // Private methods
  77414. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77415. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77416. return true;
  77417. }
  77418. return false;
  77419. };
  77420. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77421. var _this = this;
  77422. var engine = scene.getEngine();
  77423. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77424. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77425. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77426. this._volumetricLightScatteringRTT.renderList = null;
  77427. this._volumetricLightScatteringRTT.renderParticles = false;
  77428. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77429. var camera = this.getCamera();
  77430. if (camera) {
  77431. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77432. }
  77433. else {
  77434. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77435. }
  77436. // Custom render function for submeshes
  77437. var renderSubMesh = function (subMesh) {
  77438. var mesh = subMesh.getRenderingMesh();
  77439. if (_this._meshExcluded(mesh)) {
  77440. return;
  77441. }
  77442. var material = subMesh.getMaterial();
  77443. if (!material) {
  77444. return;
  77445. }
  77446. var scene = mesh.getScene();
  77447. var engine = scene.getEngine();
  77448. // Culling
  77449. engine.setState(material.backFaceCulling);
  77450. // Managing instances
  77451. var batch = mesh._getInstancesRenderList(subMesh._id);
  77452. if (batch.mustReturn) {
  77453. return;
  77454. }
  77455. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77456. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77457. var effect = _this._volumetricLightScatteringPass;
  77458. if (mesh === _this.mesh) {
  77459. if (subMesh.effect) {
  77460. effect = subMesh.effect;
  77461. }
  77462. else {
  77463. effect = material.getEffect();
  77464. }
  77465. }
  77466. engine.enableEffect(effect);
  77467. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77468. if (mesh === _this.mesh) {
  77469. material.bind(mesh.getWorldMatrix(), mesh);
  77470. }
  77471. else {
  77472. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77473. // Alpha test
  77474. if (material && material.needAlphaTesting()) {
  77475. var alphaTexture = material.getAlphaTestTexture();
  77476. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77477. if (alphaTexture) {
  77478. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77479. }
  77480. }
  77481. // Bones
  77482. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77483. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77484. }
  77485. }
  77486. // Draw
  77487. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77488. }
  77489. };
  77490. // Render target texture callbacks
  77491. var savedSceneClearColor;
  77492. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77493. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77494. savedSceneClearColor = scene.clearColor;
  77495. scene.clearColor = sceneClearColor;
  77496. });
  77497. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77498. scene.clearColor = savedSceneClearColor;
  77499. });
  77500. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77501. var engine = scene.getEngine();
  77502. var index;
  77503. if (depthOnlySubMeshes.length) {
  77504. engine.setColorWrite(false);
  77505. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77506. renderSubMesh(depthOnlySubMeshes.data[index]);
  77507. }
  77508. engine.setColorWrite(true);
  77509. }
  77510. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77511. renderSubMesh(opaqueSubMeshes.data[index]);
  77512. }
  77513. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77514. renderSubMesh(alphaTestSubMeshes.data[index]);
  77515. }
  77516. if (transparentSubMeshes.length) {
  77517. // Sort sub meshes
  77518. for (index = 0; index < transparentSubMeshes.length; index++) {
  77519. var submesh = transparentSubMeshes.data[index];
  77520. var boundingInfo = submesh.getBoundingInfo();
  77521. if (boundingInfo && scene.activeCamera) {
  77522. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77523. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77524. }
  77525. }
  77526. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77527. sortedArray.sort(function (a, b) {
  77528. // Alpha index first
  77529. if (a._alphaIndex > b._alphaIndex) {
  77530. return 1;
  77531. }
  77532. if (a._alphaIndex < b._alphaIndex) {
  77533. return -1;
  77534. }
  77535. // Then distance to camera
  77536. if (a._distanceToCamera < b._distanceToCamera) {
  77537. return 1;
  77538. }
  77539. if (a._distanceToCamera > b._distanceToCamera) {
  77540. return -1;
  77541. }
  77542. return 0;
  77543. });
  77544. // Render sub meshes
  77545. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77546. for (index = 0; index < sortedArray.length; index++) {
  77547. renderSubMesh(sortedArray[index]);
  77548. }
  77549. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77550. }
  77551. };
  77552. };
  77553. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77554. var transform = scene.getTransformMatrix();
  77555. var meshPosition;
  77556. if (this.useCustomMeshPosition) {
  77557. meshPosition = this.customMeshPosition;
  77558. }
  77559. else if (this.attachedNode) {
  77560. meshPosition = this.attachedNode.position;
  77561. }
  77562. else {
  77563. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77564. }
  77565. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77566. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77567. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77568. if (this.invert)
  77569. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77570. };
  77571. // Static methods
  77572. /**
  77573. * Creates a default mesh for the Volumeric Light Scattering post-process
  77574. * @param {string} The mesh name
  77575. * @param {BABYLON.Scene} The scene where to create the mesh
  77576. * @return {BABYLON.Mesh} the default mesh
  77577. */
  77578. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77579. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77580. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77581. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77582. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77583. mesh.material = material;
  77584. return mesh;
  77585. };
  77586. __decorate([
  77587. BABYLON.serializeAsVector3()
  77588. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77589. __decorate([
  77590. BABYLON.serialize()
  77591. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77592. __decorate([
  77593. BABYLON.serialize()
  77594. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77595. __decorate([
  77596. BABYLON.serializeAsMeshReference()
  77597. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77598. __decorate([
  77599. BABYLON.serialize()
  77600. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77601. __decorate([
  77602. BABYLON.serialize()
  77603. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77604. __decorate([
  77605. BABYLON.serialize()
  77606. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77607. __decorate([
  77608. BABYLON.serialize()
  77609. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77610. __decorate([
  77611. BABYLON.serialize()
  77612. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77613. return VolumetricLightScatteringPostProcess;
  77614. }(BABYLON.PostProcess));
  77615. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77616. })(BABYLON || (BABYLON = {}));
  77617. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77618. //
  77619. // This post-process allows the modification of rendered colors by using
  77620. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77621. //
  77622. // The object needs to be provided an url to a texture containing the color
  77623. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77624. // Use an image editing software to tweak the LUT to match your needs.
  77625. //
  77626. // For an example of a color LUT, see here:
  77627. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77628. // For explanations on color grading, see here:
  77629. // http://udn.epicgames.com/Three/ColorGrading.html
  77630. //
  77631. var BABYLON;
  77632. (function (BABYLON) {
  77633. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77634. __extends(ColorCorrectionPostProcess, _super);
  77635. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77636. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77637. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77638. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77639. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77640. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77641. _this.onApply = function (effect) {
  77642. effect.setTexture("colorTable", _this._colorTableTexture);
  77643. };
  77644. return _this;
  77645. }
  77646. return ColorCorrectionPostProcess;
  77647. }(BABYLON.PostProcess));
  77648. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77649. })(BABYLON || (BABYLON = {}));
  77650. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77651. var BABYLON;
  77652. (function (BABYLON) {
  77653. /** Defines operator used for tonemapping */
  77654. var TonemappingOperator;
  77655. (function (TonemappingOperator) {
  77656. /** Hable */
  77657. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77658. /** Reinhard */
  77659. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77660. /** HejiDawson */
  77661. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77662. /** Photographic */
  77663. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77664. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77665. ;
  77666. /**
  77667. * Defines a post process to apply tone mapping
  77668. */
  77669. var TonemapPostProcess = /** @class */ (function (_super) {
  77670. __extends(TonemapPostProcess, _super);
  77671. /**
  77672. * Creates a new TonemapPostProcess
  77673. * @param name defines the name of the postprocess
  77674. * @param _operator defines the operator to use
  77675. * @param exposureAdjustment defines the required exposure adjustement
  77676. * @param camera defines the camera to use (can be null)
  77677. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77678. * @param engine defines the hosting engine (can be ignore if camera is set)
  77679. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77680. */
  77681. function TonemapPostProcess(name, _operator,
  77682. /** Defines the required exposure adjustement */
  77683. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77684. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77685. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77686. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77687. _this._operator = _operator;
  77688. _this.exposureAdjustment = exposureAdjustment;
  77689. var defines = "#define ";
  77690. if (_this._operator === TonemappingOperator.Hable)
  77691. defines += "HABLE_TONEMAPPING";
  77692. else if (_this._operator === TonemappingOperator.Reinhard)
  77693. defines += "REINHARD_TONEMAPPING";
  77694. else if (_this._operator === TonemappingOperator.HejiDawson)
  77695. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77696. else if (_this._operator === TonemappingOperator.Photographic)
  77697. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77698. //sadly a second call to create the effect.
  77699. _this.updateEffect(defines);
  77700. _this.onApply = function (effect) {
  77701. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77702. };
  77703. return _this;
  77704. }
  77705. return TonemapPostProcess;
  77706. }(BABYLON.PostProcess));
  77707. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77708. })(BABYLON || (BABYLON = {}));
  77709. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77710. var BABYLON;
  77711. (function (BABYLON) {
  77712. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77713. __extends(DisplayPassPostProcess, _super);
  77714. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77715. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77716. }
  77717. return DisplayPassPostProcess;
  77718. }(BABYLON.PostProcess));
  77719. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77720. })(BABYLON || (BABYLON = {}));
  77721. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77722. var BABYLON;
  77723. (function (BABYLON) {
  77724. var HighlightsPostProcess = /** @class */ (function (_super) {
  77725. __extends(HighlightsPostProcess, _super);
  77726. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77727. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77728. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77729. }
  77730. return HighlightsPostProcess;
  77731. }(BABYLON.PostProcess));
  77732. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77733. })(BABYLON || (BABYLON = {}));
  77734. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77735. var BABYLON;
  77736. (function (BABYLON) {
  77737. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77738. __extends(ImageProcessingPostProcess, _super);
  77739. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77740. if (camera === void 0) { camera = null; }
  77741. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77742. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77743. _this._fromLinearSpace = true;
  77744. /**
  77745. * Defines cache preventing GC.
  77746. */
  77747. _this._defines = {
  77748. IMAGEPROCESSING: false,
  77749. VIGNETTE: false,
  77750. VIGNETTEBLENDMODEMULTIPLY: false,
  77751. VIGNETTEBLENDMODEOPAQUE: false,
  77752. TONEMAPPING: false,
  77753. CONTRAST: false,
  77754. COLORCURVES: false,
  77755. COLORGRADING: false,
  77756. COLORGRADING3D: false,
  77757. FROMLINEARSPACE: false,
  77758. SAMPLER3DGREENDEPTH: false,
  77759. SAMPLER3DBGRMAP: false,
  77760. IMAGEPROCESSINGPOSTPROCESS: false,
  77761. EXPOSURE: false,
  77762. };
  77763. // Setup the configuration as forced by the constructor. This would then not force the
  77764. // scene materials output in linear space and let untouched the default forward pass.
  77765. if (imageProcessingConfiguration) {
  77766. imageProcessingConfiguration.applyByPostProcess = true;
  77767. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77768. // This will cause the shader to be compiled
  77769. _this.fromLinearSpace = false;
  77770. }
  77771. // Setup the default processing configuration to the scene.
  77772. else {
  77773. _this._attachImageProcessingConfiguration(null, true);
  77774. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77775. }
  77776. _this.onApply = function (effect) {
  77777. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77778. };
  77779. return _this;
  77780. }
  77781. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77782. /**
  77783. * Gets the image processing configuration used either in this material.
  77784. */
  77785. get: function () {
  77786. return this._imageProcessingConfiguration;
  77787. },
  77788. /**
  77789. * Sets the Default image processing configuration used either in the this material.
  77790. *
  77791. * If sets to null, the scene one is in use.
  77792. */
  77793. set: function (value) {
  77794. this._attachImageProcessingConfiguration(value);
  77795. },
  77796. enumerable: true,
  77797. configurable: true
  77798. });
  77799. /**
  77800. * Attaches a new image processing configuration to the PBR Material.
  77801. * @param configuration
  77802. */
  77803. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77804. var _this = this;
  77805. if (doNotBuild === void 0) { doNotBuild = false; }
  77806. if (configuration === this._imageProcessingConfiguration) {
  77807. return;
  77808. }
  77809. // Detaches observer.
  77810. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77811. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77812. }
  77813. // Pick the scene configuration if needed.
  77814. if (!configuration) {
  77815. var scene = null;
  77816. var engine = this.getEngine();
  77817. var camera = this.getCamera();
  77818. if (camera) {
  77819. scene = camera.getScene();
  77820. }
  77821. else if (engine && engine.scenes) {
  77822. var scenes = engine.scenes;
  77823. scene = scenes[scenes.length - 1];
  77824. }
  77825. else {
  77826. scene = BABYLON.Engine.LastCreatedScene;
  77827. }
  77828. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77829. }
  77830. else {
  77831. this._imageProcessingConfiguration = configuration;
  77832. }
  77833. // Attaches observer.
  77834. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77835. _this._updateParameters();
  77836. });
  77837. // Ensure the effect will be rebuilt.
  77838. if (!doNotBuild) {
  77839. this._updateParameters();
  77840. }
  77841. };
  77842. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77843. /**
  77844. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77845. */
  77846. get: function () {
  77847. return this.imageProcessingConfiguration.colorCurves;
  77848. },
  77849. /**
  77850. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77851. */
  77852. set: function (value) {
  77853. this.imageProcessingConfiguration.colorCurves = value;
  77854. },
  77855. enumerable: true,
  77856. configurable: true
  77857. });
  77858. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77859. /**
  77860. * Gets wether the color curves effect is enabled.
  77861. */
  77862. get: function () {
  77863. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77864. },
  77865. /**
  77866. * Sets wether the color curves effect is enabled.
  77867. */
  77868. set: function (value) {
  77869. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77870. },
  77871. enumerable: true,
  77872. configurable: true
  77873. });
  77874. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77875. /**
  77876. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77877. */
  77878. get: function () {
  77879. return this.imageProcessingConfiguration.colorGradingTexture;
  77880. },
  77881. /**
  77882. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77883. */
  77884. set: function (value) {
  77885. this.imageProcessingConfiguration.colorGradingTexture = value;
  77886. },
  77887. enumerable: true,
  77888. configurable: true
  77889. });
  77890. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77891. /**
  77892. * Gets wether the color grading effect is enabled.
  77893. */
  77894. get: function () {
  77895. return this.imageProcessingConfiguration.colorGradingEnabled;
  77896. },
  77897. /**
  77898. * Gets wether the color grading effect is enabled.
  77899. */
  77900. set: function (value) {
  77901. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77902. },
  77903. enumerable: true,
  77904. configurable: true
  77905. });
  77906. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77907. /**
  77908. * Gets exposure used in the effect.
  77909. */
  77910. get: function () {
  77911. return this.imageProcessingConfiguration.exposure;
  77912. },
  77913. /**
  77914. * Sets exposure used in the effect.
  77915. */
  77916. set: function (value) {
  77917. this.imageProcessingConfiguration.exposure = value;
  77918. },
  77919. enumerable: true,
  77920. configurable: true
  77921. });
  77922. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77923. /**
  77924. * Gets wether tonemapping is enabled or not.
  77925. */
  77926. get: function () {
  77927. return this._imageProcessingConfiguration.toneMappingEnabled;
  77928. },
  77929. /**
  77930. * Sets wether tonemapping is enabled or not
  77931. */
  77932. set: function (value) {
  77933. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77934. },
  77935. enumerable: true,
  77936. configurable: true
  77937. });
  77938. ;
  77939. ;
  77940. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77941. /**
  77942. * Gets contrast used in the effect.
  77943. */
  77944. get: function () {
  77945. return this.imageProcessingConfiguration.contrast;
  77946. },
  77947. /**
  77948. * Sets contrast used in the effect.
  77949. */
  77950. set: function (value) {
  77951. this.imageProcessingConfiguration.contrast = value;
  77952. },
  77953. enumerable: true,
  77954. configurable: true
  77955. });
  77956. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77957. /**
  77958. * Gets Vignette stretch size.
  77959. */
  77960. get: function () {
  77961. return this.imageProcessingConfiguration.vignetteStretch;
  77962. },
  77963. /**
  77964. * Sets Vignette stretch size.
  77965. */
  77966. set: function (value) {
  77967. this.imageProcessingConfiguration.vignetteStretch = value;
  77968. },
  77969. enumerable: true,
  77970. configurable: true
  77971. });
  77972. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77973. /**
  77974. * Gets Vignette centre X Offset.
  77975. */
  77976. get: function () {
  77977. return this.imageProcessingConfiguration.vignetteCentreX;
  77978. },
  77979. /**
  77980. * Sets Vignette centre X Offset.
  77981. */
  77982. set: function (value) {
  77983. this.imageProcessingConfiguration.vignetteCentreX = value;
  77984. },
  77985. enumerable: true,
  77986. configurable: true
  77987. });
  77988. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77989. /**
  77990. * Gets Vignette centre Y Offset.
  77991. */
  77992. get: function () {
  77993. return this.imageProcessingConfiguration.vignetteCentreY;
  77994. },
  77995. /**
  77996. * Sets Vignette centre Y Offset.
  77997. */
  77998. set: function (value) {
  77999. this.imageProcessingConfiguration.vignetteCentreY = value;
  78000. },
  78001. enumerable: true,
  78002. configurable: true
  78003. });
  78004. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78005. /**
  78006. * Gets Vignette weight or intensity of the vignette effect.
  78007. */
  78008. get: function () {
  78009. return this.imageProcessingConfiguration.vignetteWeight;
  78010. },
  78011. /**
  78012. * Sets Vignette weight or intensity of the vignette effect.
  78013. */
  78014. set: function (value) {
  78015. this.imageProcessingConfiguration.vignetteWeight = value;
  78016. },
  78017. enumerable: true,
  78018. configurable: true
  78019. });
  78020. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78021. /**
  78022. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78023. * if vignetteEnabled is set to true.
  78024. */
  78025. get: function () {
  78026. return this.imageProcessingConfiguration.vignetteColor;
  78027. },
  78028. /**
  78029. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78030. * if vignetteEnabled is set to true.
  78031. */
  78032. set: function (value) {
  78033. this.imageProcessingConfiguration.vignetteColor = value;
  78034. },
  78035. enumerable: true,
  78036. configurable: true
  78037. });
  78038. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78039. /**
  78040. * Gets Camera field of view used by the Vignette effect.
  78041. */
  78042. get: function () {
  78043. return this.imageProcessingConfiguration.vignetteCameraFov;
  78044. },
  78045. /**
  78046. * Sets Camera field of view used by the Vignette effect.
  78047. */
  78048. set: function (value) {
  78049. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78050. },
  78051. enumerable: true,
  78052. configurable: true
  78053. });
  78054. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78055. /**
  78056. * Gets the vignette blend mode allowing different kind of effect.
  78057. */
  78058. get: function () {
  78059. return this.imageProcessingConfiguration.vignetteBlendMode;
  78060. },
  78061. /**
  78062. * Sets the vignette blend mode allowing different kind of effect.
  78063. */
  78064. set: function (value) {
  78065. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78066. },
  78067. enumerable: true,
  78068. configurable: true
  78069. });
  78070. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78071. /**
  78072. * Gets wether the vignette effect is enabled.
  78073. */
  78074. get: function () {
  78075. return this.imageProcessingConfiguration.vignetteEnabled;
  78076. },
  78077. /**
  78078. * Sets wether the vignette effect is enabled.
  78079. */
  78080. set: function (value) {
  78081. this.imageProcessingConfiguration.vignetteEnabled = value;
  78082. },
  78083. enumerable: true,
  78084. configurable: true
  78085. });
  78086. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78087. /**
  78088. * Gets wether the input of the processing is in Gamma or Linear Space.
  78089. */
  78090. get: function () {
  78091. return this._fromLinearSpace;
  78092. },
  78093. /**
  78094. * Sets wether the input of the processing is in Gamma or Linear Space.
  78095. */
  78096. set: function (value) {
  78097. if (this._fromLinearSpace === value) {
  78098. return;
  78099. }
  78100. this._fromLinearSpace = value;
  78101. this._updateParameters();
  78102. },
  78103. enumerable: true,
  78104. configurable: true
  78105. });
  78106. ImageProcessingPostProcess.prototype.getClassName = function () {
  78107. return "ImageProcessingPostProcess";
  78108. };
  78109. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78110. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78111. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78112. var defines = "";
  78113. for (var define in this._defines) {
  78114. if (this._defines[define]) {
  78115. defines += "#define " + define + ";\r\n";
  78116. }
  78117. }
  78118. var samplers = ["textureSampler"];
  78119. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78120. var uniforms = ["scale"];
  78121. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78122. this.updateEffect(defines, uniforms, samplers);
  78123. };
  78124. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78125. _super.prototype.dispose.call(this, camera);
  78126. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78127. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78128. }
  78129. this.imageProcessingConfiguration.applyByPostProcess = false;
  78130. };
  78131. __decorate([
  78132. BABYLON.serialize()
  78133. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78134. return ImageProcessingPostProcess;
  78135. }(BABYLON.PostProcess));
  78136. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78137. })(BABYLON || (BABYLON = {}));
  78138. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78139. var BABYLON;
  78140. (function (BABYLON) {
  78141. /**
  78142. * Class used to store bone information
  78143. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78144. */
  78145. var Bone = /** @class */ (function (_super) {
  78146. __extends(Bone, _super);
  78147. /**
  78148. * Create a new bone
  78149. * @param name defines the bone name
  78150. * @param skeleton defines the parent skeleton
  78151. * @param parentBone defines the parent (can be null if the bone is the root)
  78152. * @param localMatrix defines the local matrix
  78153. * @param restPose defines the rest pose matrix
  78154. * @param baseMatrix defines the base matrix
  78155. * @param index defines index of the bone in the hiearchy
  78156. */
  78157. function Bone(
  78158. /**
  78159. * defines the bone name
  78160. */
  78161. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78162. if (parentBone === void 0) { parentBone = null; }
  78163. if (localMatrix === void 0) { localMatrix = null; }
  78164. if (restPose === void 0) { restPose = null; }
  78165. if (baseMatrix === void 0) { baseMatrix = null; }
  78166. if (index === void 0) { index = null; }
  78167. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78168. _this.name = name;
  78169. /**
  78170. * Gets the list of child bones
  78171. */
  78172. _this.children = new Array();
  78173. /** Gets the animations associated with this bone */
  78174. _this.animations = new Array();
  78175. /**
  78176. * @hidden Internal only
  78177. * Set this value to map this bone to a different index in the transform matrices
  78178. * Set this value to -1 to exclude the bone from the transform matrices
  78179. */
  78180. _this._index = null;
  78181. _this._absoluteTransform = new BABYLON.Matrix();
  78182. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78183. _this._scalingDeterminant = 1;
  78184. _this._worldTransform = new BABYLON.Matrix();
  78185. _this._needToDecompose = true;
  78186. _this._needToCompose = false;
  78187. _this._skeleton = skeleton;
  78188. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78189. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78190. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78191. _this._index = index;
  78192. skeleton.bones.push(_this);
  78193. _this.setParent(parentBone, false);
  78194. if (baseMatrix || localMatrix) {
  78195. _this._updateDifferenceMatrix();
  78196. }
  78197. return _this;
  78198. }
  78199. Object.defineProperty(Bone.prototype, "_matrix", {
  78200. /** @hidden */
  78201. get: function () {
  78202. this._compose();
  78203. return this._localMatrix;
  78204. },
  78205. /** @hidden */
  78206. set: function (value) {
  78207. this._localMatrix.copyFrom(value);
  78208. this._needToDecompose = true;
  78209. },
  78210. enumerable: true,
  78211. configurable: true
  78212. });
  78213. // Members
  78214. /**
  78215. * Gets the parent skeleton
  78216. * @returns a skeleton
  78217. */
  78218. Bone.prototype.getSkeleton = function () {
  78219. return this._skeleton;
  78220. };
  78221. /**
  78222. * Gets parent bone
  78223. * @returns a bone or null if the bone is the root of the bone hierarchy
  78224. */
  78225. Bone.prototype.getParent = function () {
  78226. return this._parent;
  78227. };
  78228. /**
  78229. * Sets the parent bone
  78230. * @param parent defines the parent (can be null if the bone is the root)
  78231. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78232. */
  78233. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78234. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78235. if (this._parent === parent) {
  78236. return;
  78237. }
  78238. if (this._parent) {
  78239. var index = this._parent.children.indexOf(this);
  78240. if (index !== -1) {
  78241. this._parent.children.splice(index, 1);
  78242. }
  78243. }
  78244. this._parent = parent;
  78245. if (this._parent) {
  78246. this._parent.children.push(this);
  78247. }
  78248. if (updateDifferenceMatrix) {
  78249. this._updateDifferenceMatrix();
  78250. }
  78251. this.markAsDirty();
  78252. };
  78253. /**
  78254. * Gets the local matrix
  78255. * @returns a matrix
  78256. */
  78257. Bone.prototype.getLocalMatrix = function () {
  78258. this._compose();
  78259. return this._localMatrix;
  78260. };
  78261. /**
  78262. * Gets the base matrix (initial matrix which remains unchanged)
  78263. * @returns a matrix
  78264. */
  78265. Bone.prototype.getBaseMatrix = function () {
  78266. return this._baseMatrix;
  78267. };
  78268. /**
  78269. * Gets the rest pose matrix
  78270. * @returns a matrix
  78271. */
  78272. Bone.prototype.getRestPose = function () {
  78273. return this._restPose;
  78274. };
  78275. /**
  78276. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78277. */
  78278. Bone.prototype.getWorldMatrix = function () {
  78279. return this._worldTransform;
  78280. };
  78281. /**
  78282. * Sets the local matrix to rest pose matrix
  78283. */
  78284. Bone.prototype.returnToRest = function () {
  78285. this.updateMatrix(this._restPose.clone());
  78286. };
  78287. /**
  78288. * Gets the inverse of the absolute transform matrix.
  78289. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78290. * @returns a matrix
  78291. */
  78292. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78293. return this._invertedAbsoluteTransform;
  78294. };
  78295. /**
  78296. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78297. * @returns a matrix
  78298. */
  78299. Bone.prototype.getAbsoluteTransform = function () {
  78300. return this._absoluteTransform;
  78301. };
  78302. Object.defineProperty(Bone.prototype, "position", {
  78303. // Properties (matches AbstractMesh properties)
  78304. /** Gets or sets current position (in local space) */
  78305. get: function () {
  78306. this._decompose();
  78307. return this._localPosition;
  78308. },
  78309. set: function (newPosition) {
  78310. this._decompose();
  78311. this._localPosition.copyFrom(newPosition);
  78312. this._markAsDirtyAndCompose();
  78313. },
  78314. enumerable: true,
  78315. configurable: true
  78316. });
  78317. Object.defineProperty(Bone.prototype, "rotation", {
  78318. /** Gets or sets current rotation (in local space) */
  78319. get: function () {
  78320. return this.getRotation();
  78321. },
  78322. set: function (newRotation) {
  78323. this.setRotation(newRotation);
  78324. },
  78325. enumerable: true,
  78326. configurable: true
  78327. });
  78328. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78329. /** Gets or sets current rotation quaternion (in local space) */
  78330. get: function () {
  78331. this._decompose();
  78332. return this._localRotation;
  78333. },
  78334. set: function (newRotation) {
  78335. this.setRotationQuaternion(newRotation);
  78336. },
  78337. enumerable: true,
  78338. configurable: true
  78339. });
  78340. Object.defineProperty(Bone.prototype, "scaling", {
  78341. /** Gets or sets current scaling (in local space) */
  78342. get: function () {
  78343. return this.getScale();
  78344. },
  78345. set: function (newScaling) {
  78346. this.setScale(newScaling);
  78347. },
  78348. enumerable: true,
  78349. configurable: true
  78350. });
  78351. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78352. /**
  78353. * Gets the animation properties override
  78354. */
  78355. get: function () {
  78356. return this._skeleton.animationPropertiesOverride;
  78357. },
  78358. enumerable: true,
  78359. configurable: true
  78360. });
  78361. // Methods
  78362. Bone.prototype._decompose = function () {
  78363. if (!this._needToDecompose) {
  78364. return;
  78365. }
  78366. this._needToDecompose = false;
  78367. if (!this._localScaling) {
  78368. this._localScaling = BABYLON.Vector3.Zero();
  78369. this._localRotation = BABYLON.Quaternion.Zero();
  78370. this._localPosition = BABYLON.Vector3.Zero();
  78371. }
  78372. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78373. };
  78374. Bone.prototype._compose = function () {
  78375. if (!this._needToCompose) {
  78376. return;
  78377. }
  78378. this._needToCompose = false;
  78379. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78380. };
  78381. /**
  78382. * Update the base and local matrices
  78383. * @param matrix defines the new base or local matrix
  78384. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78385. * @param updateLocalMatrix defines if the local matrix should be updated
  78386. */
  78387. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78388. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78389. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78390. this._baseMatrix.copyFrom(matrix);
  78391. if (updateDifferenceMatrix) {
  78392. this._updateDifferenceMatrix();
  78393. }
  78394. if (updateLocalMatrix) {
  78395. this._localMatrix.copyFrom(matrix);
  78396. this._markAsDirtyAndDecompose();
  78397. }
  78398. else {
  78399. this.markAsDirty();
  78400. }
  78401. };
  78402. /** @hidden */
  78403. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78404. if (updateChildren === void 0) { updateChildren = true; }
  78405. if (!rootMatrix) {
  78406. rootMatrix = this._baseMatrix;
  78407. }
  78408. if (this._parent) {
  78409. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78410. }
  78411. else {
  78412. this._absoluteTransform.copyFrom(rootMatrix);
  78413. }
  78414. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78415. if (updateChildren) {
  78416. for (var index = 0; index < this.children.length; index++) {
  78417. this.children[index]._updateDifferenceMatrix();
  78418. }
  78419. }
  78420. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78421. };
  78422. /**
  78423. * Flag the bone as dirty (Forcing it to update everything)
  78424. */
  78425. Bone.prototype.markAsDirty = function () {
  78426. this._currentRenderId++;
  78427. this._childRenderId++;
  78428. this._skeleton._markAsDirty();
  78429. };
  78430. Bone.prototype._markAsDirtyAndCompose = function () {
  78431. this.markAsDirty();
  78432. this._needToCompose = true;
  78433. };
  78434. Bone.prototype._markAsDirtyAndDecompose = function () {
  78435. this.markAsDirty();
  78436. this._needToDecompose = true;
  78437. };
  78438. /**
  78439. * Copy an animation range from another bone
  78440. * @param source defines the source bone
  78441. * @param rangeName defines the range name to copy
  78442. * @param frameOffset defines the frame offset
  78443. * @param rescaleAsRequired defines if rescaling must be applied if required
  78444. * @param skelDimensionsRatio defines the scaling ratio
  78445. * @returns true if operation was successful
  78446. */
  78447. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78448. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78449. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78450. // all animation may be coming from a library skeleton, so may need to create animation
  78451. if (this.animations.length === 0) {
  78452. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78453. this.animations[0].setKeys([]);
  78454. }
  78455. // get animation info / verify there is such a range from the source bone
  78456. var sourceRange = source.animations[0].getRange(rangeName);
  78457. if (!sourceRange) {
  78458. return false;
  78459. }
  78460. var from = sourceRange.from;
  78461. var to = sourceRange.to;
  78462. var sourceKeys = source.animations[0].getKeys();
  78463. // rescaling prep
  78464. var sourceBoneLength = source.length;
  78465. var sourceParent = source.getParent();
  78466. var parent = this.getParent();
  78467. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78468. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78469. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78470. var destKeys = this.animations[0].getKeys();
  78471. // loop vars declaration
  78472. var orig;
  78473. var origTranslation;
  78474. var mat;
  78475. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78476. orig = sourceKeys[key];
  78477. if (orig.frame >= from && orig.frame <= to) {
  78478. if (rescaleAsRequired) {
  78479. mat = orig.value.clone();
  78480. // scale based on parent ratio, when bone has parent
  78481. if (parentScalingReqd) {
  78482. origTranslation = mat.getTranslation();
  78483. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78484. // scale based on skeleton dimension ratio when root bone, and value is passed
  78485. }
  78486. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78487. origTranslation = mat.getTranslation();
  78488. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78489. // use original when root bone, and no data for skelDimensionsRatio
  78490. }
  78491. else {
  78492. mat = orig.value;
  78493. }
  78494. }
  78495. else {
  78496. mat = orig.value;
  78497. }
  78498. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78499. }
  78500. }
  78501. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78502. return true;
  78503. };
  78504. /**
  78505. * Translate the bone in local or world space
  78506. * @param vec The amount to translate the bone
  78507. * @param space The space that the translation is in
  78508. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78509. */
  78510. Bone.prototype.translate = function (vec, space, mesh) {
  78511. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78512. var lm = this.getLocalMatrix();
  78513. if (space == BABYLON.Space.LOCAL) {
  78514. lm.m[12] += vec.x;
  78515. lm.m[13] += vec.y;
  78516. lm.m[14] += vec.z;
  78517. }
  78518. else {
  78519. var wm = null;
  78520. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78521. if (mesh) {
  78522. wm = mesh.getWorldMatrix();
  78523. }
  78524. this._skeleton.computeAbsoluteTransforms();
  78525. var tmat = Bone._tmpMats[0];
  78526. var tvec = Bone._tmpVecs[0];
  78527. if (this._parent) {
  78528. if (mesh && wm) {
  78529. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78530. tmat.multiplyToRef(wm, tmat);
  78531. }
  78532. else {
  78533. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78534. }
  78535. }
  78536. tmat.m[12] = 0;
  78537. tmat.m[13] = 0;
  78538. tmat.m[14] = 0;
  78539. tmat.invert();
  78540. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78541. lm.m[12] += tvec.x;
  78542. lm.m[13] += tvec.y;
  78543. lm.m[14] += tvec.z;
  78544. }
  78545. this._markAsDirtyAndDecompose();
  78546. };
  78547. /**
  78548. * Set the postion of the bone in local or world space
  78549. * @param position The position to set the bone
  78550. * @param space The space that the position is in
  78551. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78552. */
  78553. Bone.prototype.setPosition = function (position, space, mesh) {
  78554. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78555. var lm = this.getLocalMatrix();
  78556. if (space == BABYLON.Space.LOCAL) {
  78557. lm.m[12] = position.x;
  78558. lm.m[13] = position.y;
  78559. lm.m[14] = position.z;
  78560. }
  78561. else {
  78562. var wm = null;
  78563. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78564. if (mesh) {
  78565. wm = mesh.getWorldMatrix();
  78566. }
  78567. this._skeleton.computeAbsoluteTransforms();
  78568. var tmat = Bone._tmpMats[0];
  78569. var vec = Bone._tmpVecs[0];
  78570. if (this._parent) {
  78571. if (mesh && wm) {
  78572. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78573. tmat.multiplyToRef(wm, tmat);
  78574. }
  78575. else {
  78576. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78577. }
  78578. }
  78579. tmat.invert();
  78580. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78581. lm.m[12] = vec.x;
  78582. lm.m[13] = vec.y;
  78583. lm.m[14] = vec.z;
  78584. }
  78585. this._markAsDirtyAndDecompose();
  78586. };
  78587. /**
  78588. * Set the absolute position of the bone (world space)
  78589. * @param position The position to set the bone
  78590. * @param mesh The mesh that this bone is attached to
  78591. */
  78592. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78593. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78594. };
  78595. /**
  78596. * Scale the bone on the x, y and z axes (in local space)
  78597. * @param x The amount to scale the bone on the x axis
  78598. * @param y The amount to scale the bone on the y axis
  78599. * @param z The amount to scale the bone on the z axis
  78600. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78601. */
  78602. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78603. if (scaleChildren === void 0) { scaleChildren = false; }
  78604. var locMat = this.getLocalMatrix();
  78605. // Apply new scaling on top of current local matrix
  78606. var scaleMat = Bone._tmpMats[0];
  78607. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78608. scaleMat.multiplyToRef(locMat, locMat);
  78609. // Invert scaling matrix and apply the inverse to all children
  78610. scaleMat.invert();
  78611. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78612. var child = _a[_i];
  78613. var cm = child.getLocalMatrix();
  78614. cm.multiplyToRef(scaleMat, cm);
  78615. cm.m[12] *= x;
  78616. cm.m[13] *= y;
  78617. cm.m[14] *= z;
  78618. child._markAsDirtyAndDecompose();
  78619. }
  78620. this._markAsDirtyAndDecompose();
  78621. if (scaleChildren) {
  78622. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78623. var child = _c[_b];
  78624. child.scale(x, y, z, scaleChildren);
  78625. }
  78626. }
  78627. };
  78628. /**
  78629. * Set the bone scaling in local space
  78630. * @param scale defines the scaling vector
  78631. */
  78632. Bone.prototype.setScale = function (scale) {
  78633. this._decompose();
  78634. this._localScaling.copyFrom(scale);
  78635. this._markAsDirtyAndCompose();
  78636. };
  78637. /**
  78638. * Gets the current scaling in local space
  78639. * @returns the current scaling vector
  78640. */
  78641. Bone.prototype.getScale = function () {
  78642. this._decompose();
  78643. return this._localScaling;
  78644. };
  78645. /**
  78646. * Gets the current scaling in local space and stores it in a target vector
  78647. * @param result defines the target vector
  78648. */
  78649. Bone.prototype.getScaleToRef = function (result) {
  78650. this._decompose();
  78651. result.copyFrom(this._localScaling);
  78652. };
  78653. /**
  78654. * Set the yaw, pitch, and roll of the bone in local or world space
  78655. * @param yaw The rotation of the bone on the y axis
  78656. * @param pitch The rotation of the bone on the x axis
  78657. * @param roll The rotation of the bone on the z axis
  78658. * @param space The space that the axes of rotation are in
  78659. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78660. */
  78661. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78663. if (space === BABYLON.Space.LOCAL) {
  78664. var quat = Bone._tmpQuat;
  78665. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78666. this.setRotationQuaternion(quat, space, mesh);
  78667. return;
  78668. }
  78669. var rotMatInv = Bone._tmpMats[0];
  78670. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78671. return;
  78672. }
  78673. var rotMat = Bone._tmpMats[1];
  78674. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78675. rotMatInv.multiplyToRef(rotMat, rotMat);
  78676. this._rotateWithMatrix(rotMat, space, mesh);
  78677. };
  78678. /**
  78679. * Add a rotation to the bone on an axis in local or world space
  78680. * @param axis The axis to rotate the bone on
  78681. * @param amount The amount to rotate the bone
  78682. * @param space The space that the axis is in
  78683. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78684. */
  78685. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78687. var rmat = Bone._tmpMats[0];
  78688. rmat.m[12] = 0;
  78689. rmat.m[13] = 0;
  78690. rmat.m[14] = 0;
  78691. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78692. this._rotateWithMatrix(rmat, space, mesh);
  78693. };
  78694. /**
  78695. * Set the rotation of the bone to a particular axis angle in local or world space
  78696. * @param axis The axis to rotate the bone on
  78697. * @param angle The angle that the bone should be rotated to
  78698. * @param space The space that the axis is in
  78699. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78700. */
  78701. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78702. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78703. if (space === BABYLON.Space.LOCAL) {
  78704. var quat = Bone._tmpQuat;
  78705. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78706. this.setRotationQuaternion(quat, space, mesh);
  78707. return;
  78708. }
  78709. var rotMatInv = Bone._tmpMats[0];
  78710. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78711. return;
  78712. }
  78713. var rotMat = Bone._tmpMats[1];
  78714. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78715. rotMatInv.multiplyToRef(rotMat, rotMat);
  78716. this._rotateWithMatrix(rotMat, space, mesh);
  78717. };
  78718. /**
  78719. * Set the euler rotation of the bone in local of world space
  78720. * @param rotation The euler rotation that the bone should be set to
  78721. * @param space The space that the rotation is in
  78722. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78723. */
  78724. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78725. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78726. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78727. };
  78728. /**
  78729. * Set the quaternion rotation of the bone in local of world space
  78730. * @param quat The quaternion rotation that the bone should be set to
  78731. * @param space The space that the rotation is in
  78732. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78733. */
  78734. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78736. if (space === BABYLON.Space.LOCAL) {
  78737. this._decompose();
  78738. this._localRotation.copyFrom(quat);
  78739. this._markAsDirtyAndCompose();
  78740. return;
  78741. }
  78742. var rotMatInv = Bone._tmpMats[0];
  78743. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78744. return;
  78745. }
  78746. var rotMat = Bone._tmpMats[1];
  78747. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78748. rotMatInv.multiplyToRef(rotMat, rotMat);
  78749. this._rotateWithMatrix(rotMat, space, mesh);
  78750. };
  78751. /**
  78752. * Set the rotation matrix of the bone in local of world space
  78753. * @param rotMat The rotation matrix that the bone should be set to
  78754. * @param space The space that the rotation is in
  78755. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78756. */
  78757. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78758. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78759. if (space === BABYLON.Space.LOCAL) {
  78760. var quat = Bone._tmpQuat;
  78761. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78762. this.setRotationQuaternion(quat, space, mesh);
  78763. return;
  78764. }
  78765. var rotMatInv = Bone._tmpMats[0];
  78766. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78767. return;
  78768. }
  78769. var rotMat2 = Bone._tmpMats[1];
  78770. rotMat2.copyFrom(rotMat);
  78771. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78772. this._rotateWithMatrix(rotMat2, space, mesh);
  78773. };
  78774. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78776. var lmat = this.getLocalMatrix();
  78777. var lx = lmat.m[12];
  78778. var ly = lmat.m[13];
  78779. var lz = lmat.m[14];
  78780. var parent = this.getParent();
  78781. var parentScale = Bone._tmpMats[3];
  78782. var parentScaleInv = Bone._tmpMats[4];
  78783. if (parent && space == BABYLON.Space.WORLD) {
  78784. if (mesh) {
  78785. parentScale.copyFrom(mesh.getWorldMatrix());
  78786. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78787. }
  78788. else {
  78789. parentScale.copyFrom(parent.getAbsoluteTransform());
  78790. }
  78791. parentScaleInv.copyFrom(parentScale);
  78792. parentScaleInv.invert();
  78793. lmat.multiplyToRef(parentScale, lmat);
  78794. lmat.multiplyToRef(rmat, lmat);
  78795. lmat.multiplyToRef(parentScaleInv, lmat);
  78796. }
  78797. else {
  78798. if (space == BABYLON.Space.WORLD && mesh) {
  78799. parentScale.copyFrom(mesh.getWorldMatrix());
  78800. parentScaleInv.copyFrom(parentScale);
  78801. parentScaleInv.invert();
  78802. lmat.multiplyToRef(parentScale, lmat);
  78803. lmat.multiplyToRef(rmat, lmat);
  78804. lmat.multiplyToRef(parentScaleInv, lmat);
  78805. }
  78806. else {
  78807. lmat.multiplyToRef(rmat, lmat);
  78808. }
  78809. }
  78810. lmat.m[12] = lx;
  78811. lmat.m[13] = ly;
  78812. lmat.m[14] = lz;
  78813. this.computeAbsoluteTransforms();
  78814. this._markAsDirtyAndDecompose();
  78815. };
  78816. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78817. var scaleMatrix = Bone._tmpMats[2];
  78818. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78819. if (mesh) {
  78820. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78821. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78822. }
  78823. rotMatInv.invert();
  78824. if (isNaN(rotMatInv.m[0])) {
  78825. // Matrix failed to invert.
  78826. // This can happen if scale is zero for example.
  78827. return false;
  78828. }
  78829. scaleMatrix.m[0] *= this._scalingDeterminant;
  78830. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78831. return true;
  78832. };
  78833. /**
  78834. * Get the position of the bone in local or world space
  78835. * @param space The space that the returned position is in
  78836. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78837. * @returns The position of the bone
  78838. */
  78839. Bone.prototype.getPosition = function (space, mesh) {
  78840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78841. if (mesh === void 0) { mesh = null; }
  78842. var pos = BABYLON.Vector3.Zero();
  78843. this.getPositionToRef(space, mesh, pos);
  78844. return pos;
  78845. };
  78846. /**
  78847. * Copy the position of the bone to a vector3 in local or world space
  78848. * @param space The space that the returned position is in
  78849. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78850. * @param result The vector3 to copy the position to
  78851. */
  78852. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78853. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78854. if (space == BABYLON.Space.LOCAL) {
  78855. var lm = this.getLocalMatrix();
  78856. result.x = lm.m[12];
  78857. result.y = lm.m[13];
  78858. result.z = lm.m[14];
  78859. }
  78860. else {
  78861. var wm = null;
  78862. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78863. if (mesh) {
  78864. wm = mesh.getWorldMatrix();
  78865. }
  78866. this._skeleton.computeAbsoluteTransforms();
  78867. var tmat = Bone._tmpMats[0];
  78868. if (mesh && wm) {
  78869. tmat.copyFrom(this.getAbsoluteTransform());
  78870. tmat.multiplyToRef(wm, tmat);
  78871. }
  78872. else {
  78873. tmat = this.getAbsoluteTransform();
  78874. }
  78875. result.x = tmat.m[12];
  78876. result.y = tmat.m[13];
  78877. result.z = tmat.m[14];
  78878. }
  78879. };
  78880. /**
  78881. * Get the absolute position of the bone (world space)
  78882. * @param mesh The mesh that this bone is attached to
  78883. * @returns The absolute position of the bone
  78884. */
  78885. Bone.prototype.getAbsolutePosition = function (mesh) {
  78886. if (mesh === void 0) { mesh = null; }
  78887. var pos = BABYLON.Vector3.Zero();
  78888. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78889. return pos;
  78890. };
  78891. /**
  78892. * Copy the absolute position of the bone (world space) to the result param
  78893. * @param mesh The mesh that this bone is attached to
  78894. * @param result The vector3 to copy the absolute position to
  78895. */
  78896. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78897. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78898. };
  78899. /**
  78900. * Compute the absolute transforms of this bone and its children
  78901. */
  78902. Bone.prototype.computeAbsoluteTransforms = function () {
  78903. this._compose();
  78904. if (this._parent) {
  78905. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78906. }
  78907. else {
  78908. this._absoluteTransform.copyFrom(this._localMatrix);
  78909. var poseMatrix = this._skeleton.getPoseMatrix();
  78910. if (poseMatrix) {
  78911. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78912. }
  78913. }
  78914. var children = this.children;
  78915. var len = children.length;
  78916. for (var i = 0; i < len; i++) {
  78917. children[i].computeAbsoluteTransforms();
  78918. }
  78919. };
  78920. /**
  78921. * Get the world direction from an axis that is in the local space of the bone
  78922. * @param localAxis The local direction that is used to compute the world direction
  78923. * @param mesh The mesh that this bone is attached to
  78924. * @returns The world direction
  78925. */
  78926. Bone.prototype.getDirection = function (localAxis, mesh) {
  78927. if (mesh === void 0) { mesh = null; }
  78928. var result = BABYLON.Vector3.Zero();
  78929. this.getDirectionToRef(localAxis, mesh, result);
  78930. return result;
  78931. };
  78932. /**
  78933. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78934. * @param localAxis The local direction that is used to compute the world direction
  78935. * @param mesh The mesh that this bone is attached to
  78936. * @param result The vector3 that the world direction will be copied to
  78937. */
  78938. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78939. if (mesh === void 0) { mesh = null; }
  78940. var wm = null;
  78941. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78942. if (mesh) {
  78943. wm = mesh.getWorldMatrix();
  78944. }
  78945. this._skeleton.computeAbsoluteTransforms();
  78946. var mat = Bone._tmpMats[0];
  78947. mat.copyFrom(this.getAbsoluteTransform());
  78948. if (mesh && wm) {
  78949. mat.multiplyToRef(wm, mat);
  78950. }
  78951. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78952. result.normalize();
  78953. };
  78954. /**
  78955. * Get the euler rotation of the bone in local or world space
  78956. * @param space The space that the rotation should be in
  78957. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78958. * @returns The euler rotation
  78959. */
  78960. Bone.prototype.getRotation = function (space, mesh) {
  78961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78962. if (mesh === void 0) { mesh = null; }
  78963. var result = BABYLON.Vector3.Zero();
  78964. this.getRotationToRef(space, mesh, result);
  78965. return result;
  78966. };
  78967. /**
  78968. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78969. * @param space The space that the rotation should be in
  78970. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78971. * @param result The vector3 that the rotation should be copied to
  78972. */
  78973. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78974. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78975. if (mesh === void 0) { mesh = null; }
  78976. var quat = Bone._tmpQuat;
  78977. this.getRotationQuaternionToRef(space, mesh, quat);
  78978. quat.toEulerAnglesToRef(result);
  78979. };
  78980. /**
  78981. * Get the quaternion rotation of the bone in either local or world space
  78982. * @param space The space that the rotation should be in
  78983. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78984. * @returns The quaternion rotation
  78985. */
  78986. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78987. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78988. if (mesh === void 0) { mesh = null; }
  78989. var result = BABYLON.Quaternion.Identity();
  78990. this.getRotationQuaternionToRef(space, mesh, result);
  78991. return result;
  78992. };
  78993. /**
  78994. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78995. * @param space The space that the rotation should be in
  78996. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78997. * @param result The quaternion that the rotation should be copied to
  78998. */
  78999. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79000. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79001. if (mesh === void 0) { mesh = null; }
  79002. if (space == BABYLON.Space.LOCAL) {
  79003. this._decompose();
  79004. result.copyFrom(this._localRotation);
  79005. }
  79006. else {
  79007. var mat = Bone._tmpMats[0];
  79008. var amat = this.getAbsoluteTransform();
  79009. if (mesh) {
  79010. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79011. }
  79012. else {
  79013. mat.copyFrom(amat);
  79014. }
  79015. mat.m[0] *= this._scalingDeterminant;
  79016. mat.m[1] *= this._scalingDeterminant;
  79017. mat.m[2] *= this._scalingDeterminant;
  79018. mat.decompose(undefined, result, undefined);
  79019. }
  79020. };
  79021. /**
  79022. * Get the rotation matrix of the bone in local or world space
  79023. * @param space The space that the rotation should be in
  79024. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79025. * @returns The rotation matrix
  79026. */
  79027. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79028. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79029. var result = BABYLON.Matrix.Identity();
  79030. this.getRotationMatrixToRef(space, mesh, result);
  79031. return result;
  79032. };
  79033. /**
  79034. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79035. * @param space The space that the rotation should be in
  79036. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79037. * @param result The quaternion that the rotation should be copied to
  79038. */
  79039. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79041. if (space == BABYLON.Space.LOCAL) {
  79042. this.getLocalMatrix().getRotationMatrixToRef(result);
  79043. }
  79044. else {
  79045. var mat = Bone._tmpMats[0];
  79046. var amat = this.getAbsoluteTransform();
  79047. if (mesh) {
  79048. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79049. }
  79050. else {
  79051. mat.copyFrom(amat);
  79052. }
  79053. mat.m[0] *= this._scalingDeterminant;
  79054. mat.m[1] *= this._scalingDeterminant;
  79055. mat.m[2] *= this._scalingDeterminant;
  79056. mat.getRotationMatrixToRef(result);
  79057. }
  79058. };
  79059. /**
  79060. * Get the world position of a point that is in the local space of the bone
  79061. * @param position The local position
  79062. * @param mesh The mesh that this bone is attached to
  79063. * @returns The world position
  79064. */
  79065. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79066. if (mesh === void 0) { mesh = null; }
  79067. var result = BABYLON.Vector3.Zero();
  79068. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79069. return result;
  79070. };
  79071. /**
  79072. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79073. * @param position The local position
  79074. * @param mesh The mesh that this bone is attached to
  79075. * @param result The vector3 that the world position should be copied to
  79076. */
  79077. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79078. if (mesh === void 0) { mesh = null; }
  79079. var wm = null;
  79080. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79081. if (mesh) {
  79082. wm = mesh.getWorldMatrix();
  79083. }
  79084. this._skeleton.computeAbsoluteTransforms();
  79085. var tmat = Bone._tmpMats[0];
  79086. if (mesh && wm) {
  79087. tmat.copyFrom(this.getAbsoluteTransform());
  79088. tmat.multiplyToRef(wm, tmat);
  79089. }
  79090. else {
  79091. tmat = this.getAbsoluteTransform();
  79092. }
  79093. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79094. };
  79095. /**
  79096. * Get the local position of a point that is in world space
  79097. * @param position The world position
  79098. * @param mesh The mesh that this bone is attached to
  79099. * @returns The local position
  79100. */
  79101. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79102. if (mesh === void 0) { mesh = null; }
  79103. var result = BABYLON.Vector3.Zero();
  79104. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79105. return result;
  79106. };
  79107. /**
  79108. * Get the local position of a point that is in world space and copy it to the result param
  79109. * @param position The world position
  79110. * @param mesh The mesh that this bone is attached to
  79111. * @param result The vector3 that the local position should be copied to
  79112. */
  79113. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79114. if (mesh === void 0) { mesh = null; }
  79115. var wm = null;
  79116. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79117. if (mesh) {
  79118. wm = mesh.getWorldMatrix();
  79119. }
  79120. this._skeleton.computeAbsoluteTransforms();
  79121. var tmat = Bone._tmpMats[0];
  79122. tmat.copyFrom(this.getAbsoluteTransform());
  79123. if (mesh && wm) {
  79124. tmat.multiplyToRef(wm, tmat);
  79125. }
  79126. tmat.invert();
  79127. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79128. };
  79129. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79130. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79131. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79132. return Bone;
  79133. }(BABYLON.Node));
  79134. BABYLON.Bone = Bone;
  79135. })(BABYLON || (BABYLON = {}));
  79136. //# sourceMappingURL=babylon.bone.js.map
  79137. var BABYLON;
  79138. (function (BABYLON) {
  79139. /**
  79140. * Class used to apply inverse kinematics to bones
  79141. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79142. */
  79143. var BoneIKController = /** @class */ (function () {
  79144. /**
  79145. * Creates a new BoneIKController
  79146. * @param mesh defines the mesh to control
  79147. * @param bone defines the bone to control
  79148. * @param options defines options to set up the controller
  79149. */
  79150. function BoneIKController(mesh, bone, options) {
  79151. /**
  79152. * Gets or sets the target position
  79153. */
  79154. this.targetPosition = BABYLON.Vector3.Zero();
  79155. /**
  79156. * Gets or sets the pole target position
  79157. */
  79158. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79159. /**
  79160. * Gets or sets the pole target local offset
  79161. */
  79162. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79163. /**
  79164. * Gets or sets the pole angle
  79165. */
  79166. this.poleAngle = 0;
  79167. /**
  79168. * 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)
  79169. */
  79170. this.slerpAmount = 1;
  79171. this._bone1Quat = BABYLON.Quaternion.Identity();
  79172. this._bone1Mat = BABYLON.Matrix.Identity();
  79173. this._bone2Ang = Math.PI;
  79174. this._maxAngle = Math.PI;
  79175. this._rightHandedSystem = false;
  79176. this._bendAxis = BABYLON.Vector3.Right();
  79177. this._slerping = false;
  79178. this._adjustRoll = 0;
  79179. this._bone2 = bone;
  79180. this._bone1 = bone.getParent();
  79181. if (!this._bone1) {
  79182. return;
  79183. }
  79184. this.mesh = mesh;
  79185. var bonePos = bone.getPosition();
  79186. if (bone.getAbsoluteTransform().determinant() > 0) {
  79187. this._rightHandedSystem = true;
  79188. this._bendAxis.x = 0;
  79189. this._bendAxis.y = 0;
  79190. this._bendAxis.z = -1;
  79191. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79192. this._adjustRoll = Math.PI * .5;
  79193. this._bendAxis.z = 1;
  79194. }
  79195. }
  79196. if (this._bone1.length) {
  79197. var boneScale1 = this._bone1.getScale();
  79198. var boneScale2 = this._bone2.getScale();
  79199. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79200. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79201. }
  79202. else if (this._bone1.children[0]) {
  79203. mesh.computeWorldMatrix(true);
  79204. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79205. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79206. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79207. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79208. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79209. }
  79210. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79211. this.maxAngle = Math.PI;
  79212. if (options) {
  79213. if (options.targetMesh) {
  79214. this.targetMesh = options.targetMesh;
  79215. this.targetMesh.computeWorldMatrix(true);
  79216. }
  79217. if (options.poleTargetMesh) {
  79218. this.poleTargetMesh = options.poleTargetMesh;
  79219. this.poleTargetMesh.computeWorldMatrix(true);
  79220. }
  79221. else if (options.poleTargetBone) {
  79222. this.poleTargetBone = options.poleTargetBone;
  79223. }
  79224. else if (this._bone1.getParent()) {
  79225. this.poleTargetBone = this._bone1.getParent();
  79226. }
  79227. if (options.poleTargetLocalOffset) {
  79228. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79229. }
  79230. if (options.poleAngle) {
  79231. this.poleAngle = options.poleAngle;
  79232. }
  79233. if (options.bendAxis) {
  79234. this._bendAxis.copyFrom(options.bendAxis);
  79235. }
  79236. if (options.maxAngle) {
  79237. this.maxAngle = options.maxAngle;
  79238. }
  79239. if (options.slerpAmount) {
  79240. this.slerpAmount = options.slerpAmount;
  79241. }
  79242. }
  79243. }
  79244. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79245. /**
  79246. * Gets or sets maximum allowed angle
  79247. */
  79248. get: function () {
  79249. return this._maxAngle;
  79250. },
  79251. set: function (value) {
  79252. this._setMaxAngle(value);
  79253. },
  79254. enumerable: true,
  79255. configurable: true
  79256. });
  79257. BoneIKController.prototype._setMaxAngle = function (ang) {
  79258. if (ang < 0) {
  79259. ang = 0;
  79260. }
  79261. if (ang > Math.PI || ang == undefined) {
  79262. ang = Math.PI;
  79263. }
  79264. this._maxAngle = ang;
  79265. var a = this._bone1Length;
  79266. var b = this._bone2Length;
  79267. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79268. };
  79269. /**
  79270. * Force the controller to update the bones
  79271. */
  79272. BoneIKController.prototype.update = function () {
  79273. var bone1 = this._bone1;
  79274. if (!bone1) {
  79275. return;
  79276. }
  79277. var target = this.targetPosition;
  79278. var poleTarget = this.poleTargetPosition;
  79279. var mat1 = BoneIKController._tmpMats[0];
  79280. var mat2 = BoneIKController._tmpMats[1];
  79281. if (this.targetMesh) {
  79282. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79283. }
  79284. if (this.poleTargetBone) {
  79285. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79286. }
  79287. else if (this.poleTargetMesh) {
  79288. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79289. }
  79290. var bonePos = BoneIKController._tmpVecs[0];
  79291. var zaxis = BoneIKController._tmpVecs[1];
  79292. var xaxis = BoneIKController._tmpVecs[2];
  79293. var yaxis = BoneIKController._tmpVecs[3];
  79294. var upAxis = BoneIKController._tmpVecs[4];
  79295. var _tmpQuat = BoneIKController._tmpQuat;
  79296. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79297. poleTarget.subtractToRef(bonePos, upAxis);
  79298. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79299. upAxis.y = 1;
  79300. }
  79301. else {
  79302. upAxis.normalize();
  79303. }
  79304. target.subtractToRef(bonePos, yaxis);
  79305. yaxis.normalize();
  79306. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79307. zaxis.normalize();
  79308. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79309. xaxis.normalize();
  79310. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79311. var a = this._bone1Length;
  79312. var b = this._bone2Length;
  79313. var c = BABYLON.Vector3.Distance(bonePos, target);
  79314. if (this._maxReach > 0) {
  79315. c = Math.min(this._maxReach, c);
  79316. }
  79317. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79318. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79319. if (acosa > 1) {
  79320. acosa = 1;
  79321. }
  79322. if (acosb > 1) {
  79323. acosb = 1;
  79324. }
  79325. if (acosa < -1) {
  79326. acosa = -1;
  79327. }
  79328. if (acosb < -1) {
  79329. acosb = -1;
  79330. }
  79331. var angA = Math.acos(acosa);
  79332. var angB = Math.acos(acosb);
  79333. var angC = -angA - angB;
  79334. if (this._rightHandedSystem) {
  79335. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79336. mat2.multiplyToRef(mat1, mat1);
  79337. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79338. mat2.multiplyToRef(mat1, mat1);
  79339. }
  79340. else {
  79341. var _tmpVec = BoneIKController._tmpVecs[5];
  79342. _tmpVec.copyFrom(this._bendAxis);
  79343. _tmpVec.x *= -1;
  79344. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79345. mat2.multiplyToRef(mat1, mat1);
  79346. }
  79347. if (this.poleAngle) {
  79348. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79349. mat1.multiplyToRef(mat2, mat1);
  79350. }
  79351. if (this._bone1) {
  79352. if (this.slerpAmount < 1) {
  79353. if (!this._slerping) {
  79354. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79355. }
  79356. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79357. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79358. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79359. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79360. this._slerping = true;
  79361. }
  79362. else {
  79363. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79364. this._bone1Mat.copyFrom(mat1);
  79365. this._slerping = false;
  79366. }
  79367. }
  79368. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79369. this._bone2Ang = angC;
  79370. };
  79371. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79372. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79373. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79374. return BoneIKController;
  79375. }());
  79376. BABYLON.BoneIKController = BoneIKController;
  79377. })(BABYLON || (BABYLON = {}));
  79378. //# sourceMappingURL=babylon.boneIKController.js.map
  79379. var BABYLON;
  79380. (function (BABYLON) {
  79381. /**
  79382. * Class used to make a bone look toward a point in space
  79383. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79384. */
  79385. var BoneLookController = /** @class */ (function () {
  79386. /**
  79387. * Create a BoneLookController
  79388. * @param mesh the mesh that the bone belongs to
  79389. * @param bone the bone that will be looking to the target
  79390. * @param target the target Vector3 to look at
  79391. * @param settings optional settings:
  79392. * * maxYaw: the maximum angle the bone will yaw to
  79393. * * minYaw: the minimum angle the bone will yaw to
  79394. * * maxPitch: the maximum angle the bone will pitch to
  79395. * * minPitch: the minimum angle the bone will yaw to
  79396. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79397. * * upAxis: the up axis of the coordinate system
  79398. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79399. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79400. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79401. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79402. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79403. * * adjustRoll: used to make an adjustment to the roll of the bone
  79404. **/
  79405. function BoneLookController(mesh, bone, target, options) {
  79406. /**
  79407. * The up axis of the coordinate system that is used when the bone is rotated
  79408. */
  79409. this.upAxis = BABYLON.Vector3.Up();
  79410. /**
  79411. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79412. */
  79413. this.upAxisSpace = BABYLON.Space.LOCAL;
  79414. /**
  79415. * Used to make an adjustment to the yaw of the bone
  79416. */
  79417. this.adjustYaw = 0;
  79418. /**
  79419. * Used to make an adjustment to the pitch of the bone
  79420. */
  79421. this.adjustPitch = 0;
  79422. /**
  79423. * Used to make an adjustment to the roll of the bone
  79424. */
  79425. this.adjustRoll = 0;
  79426. /**
  79427. * 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)
  79428. */
  79429. this.slerpAmount = 1;
  79430. this._boneQuat = BABYLON.Quaternion.Identity();
  79431. this._slerping = false;
  79432. this._firstFrameSkipped = false;
  79433. this._fowardAxis = BABYLON.Vector3.Forward();
  79434. this.mesh = mesh;
  79435. this.bone = bone;
  79436. this.target = target;
  79437. if (options) {
  79438. if (options.adjustYaw) {
  79439. this.adjustYaw = options.adjustYaw;
  79440. }
  79441. if (options.adjustPitch) {
  79442. this.adjustPitch = options.adjustPitch;
  79443. }
  79444. if (options.adjustRoll) {
  79445. this.adjustRoll = options.adjustRoll;
  79446. }
  79447. if (options.maxYaw != null) {
  79448. this.maxYaw = options.maxYaw;
  79449. }
  79450. else {
  79451. this.maxYaw = Math.PI;
  79452. }
  79453. if (options.minYaw != null) {
  79454. this.minYaw = options.minYaw;
  79455. }
  79456. else {
  79457. this.minYaw = -Math.PI;
  79458. }
  79459. if (options.maxPitch != null) {
  79460. this.maxPitch = options.maxPitch;
  79461. }
  79462. else {
  79463. this.maxPitch = Math.PI;
  79464. }
  79465. if (options.minPitch != null) {
  79466. this.minPitch = options.minPitch;
  79467. }
  79468. else {
  79469. this.minPitch = -Math.PI;
  79470. }
  79471. if (options.slerpAmount != null) {
  79472. this.slerpAmount = options.slerpAmount;
  79473. }
  79474. if (options.upAxis != null) {
  79475. this.upAxis = options.upAxis;
  79476. }
  79477. if (options.upAxisSpace != null) {
  79478. this.upAxisSpace = options.upAxisSpace;
  79479. }
  79480. if (options.yawAxis != null || options.pitchAxis != null) {
  79481. var newYawAxis = BABYLON.Axis.Y;
  79482. var newPitchAxis = BABYLON.Axis.X;
  79483. if (options.yawAxis != null) {
  79484. newYawAxis = options.yawAxis.clone();
  79485. newYawAxis.normalize();
  79486. }
  79487. if (options.pitchAxis != null) {
  79488. newPitchAxis = options.pitchAxis.clone();
  79489. newPitchAxis.normalize();
  79490. }
  79491. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79492. this._transformYawPitch = BABYLON.Matrix.Identity();
  79493. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79494. this._transformYawPitchInv = this._transformYawPitch.clone();
  79495. this._transformYawPitch.invert();
  79496. }
  79497. }
  79498. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79499. this.upAxisSpace = BABYLON.Space.LOCAL;
  79500. }
  79501. }
  79502. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79503. /**
  79504. * Gets or sets the minimum yaw angle that the bone can look to
  79505. */
  79506. get: function () {
  79507. return this._minYaw;
  79508. },
  79509. set: function (value) {
  79510. this._minYaw = value;
  79511. this._minYawSin = Math.sin(value);
  79512. this._minYawCos = Math.cos(value);
  79513. if (this._maxYaw != null) {
  79514. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79515. this._yawRange = this._maxYaw - this._minYaw;
  79516. }
  79517. },
  79518. enumerable: true,
  79519. configurable: true
  79520. });
  79521. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79522. /**
  79523. * Gets or sets the maximum yaw angle that the bone can look to
  79524. */
  79525. get: function () {
  79526. return this._maxYaw;
  79527. },
  79528. set: function (value) {
  79529. this._maxYaw = value;
  79530. this._maxYawSin = Math.sin(value);
  79531. this._maxYawCos = Math.cos(value);
  79532. if (this._minYaw != null) {
  79533. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79534. this._yawRange = this._maxYaw - this._minYaw;
  79535. }
  79536. },
  79537. enumerable: true,
  79538. configurable: true
  79539. });
  79540. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79541. /**
  79542. * Gets or sets the minimum pitch angle that the bone can look to
  79543. */
  79544. get: function () {
  79545. return this._minPitch;
  79546. },
  79547. set: function (value) {
  79548. this._minPitch = value;
  79549. this._minPitchTan = Math.tan(value);
  79550. },
  79551. enumerable: true,
  79552. configurable: true
  79553. });
  79554. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79555. /**
  79556. * Gets or sets the maximum pitch angle that the bone can look to
  79557. */
  79558. get: function () {
  79559. return this._maxPitch;
  79560. },
  79561. set: function (value) {
  79562. this._maxPitch = value;
  79563. this._maxPitchTan = Math.tan(value);
  79564. },
  79565. enumerable: true,
  79566. configurable: true
  79567. });
  79568. /**
  79569. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79570. */
  79571. BoneLookController.prototype.update = function () {
  79572. //skip the first frame when slerping so that the mesh rotation is correct
  79573. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79574. this._firstFrameSkipped = true;
  79575. return;
  79576. }
  79577. var bone = this.bone;
  79578. var bonePos = BoneLookController._tmpVecs[0];
  79579. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79580. var target = this.target;
  79581. var _tmpMat1 = BoneLookController._tmpMats[0];
  79582. var _tmpMat2 = BoneLookController._tmpMats[1];
  79583. var mesh = this.mesh;
  79584. var parentBone = bone.getParent();
  79585. var upAxis = BoneLookController._tmpVecs[1];
  79586. upAxis.copyFrom(this.upAxis);
  79587. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79588. if (this._transformYawPitch) {
  79589. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79590. }
  79591. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79592. }
  79593. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79594. mesh.getDirectionToRef(upAxis, upAxis);
  79595. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79596. upAxis.normalize();
  79597. }
  79598. }
  79599. var checkYaw = false;
  79600. var checkPitch = false;
  79601. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79602. checkYaw = true;
  79603. }
  79604. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79605. checkPitch = true;
  79606. }
  79607. if (checkYaw || checkPitch) {
  79608. var spaceMat = BoneLookController._tmpMats[2];
  79609. var spaceMatInv = BoneLookController._tmpMats[3];
  79610. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79611. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79612. }
  79613. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79614. spaceMat.copyFrom(mesh.getWorldMatrix());
  79615. }
  79616. else {
  79617. var forwardAxis = BoneLookController._tmpVecs[2];
  79618. forwardAxis.copyFrom(this._fowardAxis);
  79619. if (this._transformYawPitch) {
  79620. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79621. }
  79622. if (parentBone) {
  79623. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79624. }
  79625. else {
  79626. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79627. }
  79628. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79629. rightAxis.normalize();
  79630. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79631. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79632. }
  79633. spaceMat.invertToRef(spaceMatInv);
  79634. var xzlen = null;
  79635. if (checkPitch) {
  79636. var localTarget = BoneLookController._tmpVecs[3];
  79637. target.subtractToRef(bonePos, localTarget);
  79638. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79639. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79640. var pitch = Math.atan2(localTarget.y, xzlen);
  79641. var newPitch = pitch;
  79642. if (pitch > this._maxPitch) {
  79643. localTarget.y = this._maxPitchTan * xzlen;
  79644. newPitch = this._maxPitch;
  79645. }
  79646. else if (pitch < this._minPitch) {
  79647. localTarget.y = this._minPitchTan * xzlen;
  79648. newPitch = this._minPitch;
  79649. }
  79650. if (pitch != newPitch) {
  79651. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79652. localTarget.addInPlace(bonePos);
  79653. target = localTarget;
  79654. }
  79655. }
  79656. if (checkYaw) {
  79657. var localTarget = BoneLookController._tmpVecs[4];
  79658. target.subtractToRef(bonePos, localTarget);
  79659. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79660. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79661. var newYaw = yaw;
  79662. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79663. if (xzlen == null) {
  79664. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79665. }
  79666. if (this._yawRange > Math.PI) {
  79667. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79668. localTarget.z = this._maxYawCos * xzlen;
  79669. localTarget.x = this._maxYawSin * xzlen;
  79670. newYaw = this._maxYaw;
  79671. }
  79672. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79673. localTarget.z = this._minYawCos * xzlen;
  79674. localTarget.x = this._minYawSin * xzlen;
  79675. newYaw = this._minYaw;
  79676. }
  79677. }
  79678. else {
  79679. if (yaw > this._maxYaw) {
  79680. localTarget.z = this._maxYawCos * xzlen;
  79681. localTarget.x = this._maxYawSin * xzlen;
  79682. newYaw = this._maxYaw;
  79683. }
  79684. else if (yaw < this._minYaw) {
  79685. localTarget.z = this._minYawCos * xzlen;
  79686. localTarget.x = this._minYawSin * xzlen;
  79687. newYaw = this._minYaw;
  79688. }
  79689. }
  79690. }
  79691. if (this._slerping && this._yawRange > Math.PI) {
  79692. //are we going to be crossing into the min/max region?
  79693. var boneFwd = BoneLookController._tmpVecs[8];
  79694. boneFwd.copyFrom(BABYLON.Axis.Z);
  79695. if (this._transformYawPitch) {
  79696. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79697. }
  79698. var boneRotMat = BoneLookController._tmpMats[4];
  79699. this._boneQuat.toRotationMatrix(boneRotMat);
  79700. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79701. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79702. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79703. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79704. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79705. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79706. if (angBtwTar > angBtwMidYaw) {
  79707. if (xzlen == null) {
  79708. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79709. }
  79710. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79711. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79712. if (angBtwMin < angBtwMax) {
  79713. newYaw = boneYaw + Math.PI * .75;
  79714. localTarget.z = Math.cos(newYaw) * xzlen;
  79715. localTarget.x = Math.sin(newYaw) * xzlen;
  79716. }
  79717. else {
  79718. newYaw = boneYaw - Math.PI * .75;
  79719. localTarget.z = Math.cos(newYaw) * xzlen;
  79720. localTarget.x = Math.sin(newYaw) * xzlen;
  79721. }
  79722. }
  79723. }
  79724. if (yaw != newYaw) {
  79725. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79726. localTarget.addInPlace(bonePos);
  79727. target = localTarget;
  79728. }
  79729. }
  79730. }
  79731. var zaxis = BoneLookController._tmpVecs[5];
  79732. var xaxis = BoneLookController._tmpVecs[6];
  79733. var yaxis = BoneLookController._tmpVecs[7];
  79734. var _tmpQuat = BoneLookController._tmpQuat;
  79735. target.subtractToRef(bonePos, zaxis);
  79736. zaxis.normalize();
  79737. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79738. xaxis.normalize();
  79739. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79740. yaxis.normalize();
  79741. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79742. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79743. return;
  79744. }
  79745. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79746. return;
  79747. }
  79748. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79749. return;
  79750. }
  79751. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79752. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79753. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79754. }
  79755. if (this.slerpAmount < 1) {
  79756. if (!this._slerping) {
  79757. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79758. }
  79759. if (this._transformYawPitch) {
  79760. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79761. }
  79762. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79763. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79764. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79765. this._slerping = true;
  79766. }
  79767. else {
  79768. if (this._transformYawPitch) {
  79769. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79770. }
  79771. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79772. this._slerping = false;
  79773. }
  79774. };
  79775. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79776. var angDiff = ang2 - ang1;
  79777. angDiff %= Math.PI * 2;
  79778. if (angDiff > Math.PI) {
  79779. angDiff -= Math.PI * 2;
  79780. }
  79781. else if (angDiff < -Math.PI) {
  79782. angDiff += Math.PI * 2;
  79783. }
  79784. return angDiff;
  79785. };
  79786. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79787. ang1 %= (2 * Math.PI);
  79788. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79789. ang2 %= (2 * Math.PI);
  79790. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79791. var ab = 0;
  79792. if (ang1 < ang2) {
  79793. ab = ang2 - ang1;
  79794. }
  79795. else {
  79796. ab = ang1 - ang2;
  79797. }
  79798. if (ab > Math.PI) {
  79799. ab = Math.PI * 2 - ab;
  79800. }
  79801. return ab;
  79802. };
  79803. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79804. ang %= (2 * Math.PI);
  79805. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79806. ang1 %= (2 * Math.PI);
  79807. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79808. ang2 %= (2 * Math.PI);
  79809. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79810. if (ang1 < ang2) {
  79811. if (ang > ang1 && ang < ang2) {
  79812. return true;
  79813. }
  79814. }
  79815. else {
  79816. if (ang > ang2 && ang < ang1) {
  79817. return true;
  79818. }
  79819. }
  79820. return false;
  79821. };
  79822. 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()];
  79823. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79824. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79825. return BoneLookController;
  79826. }());
  79827. BABYLON.BoneLookController = BoneLookController;
  79828. })(BABYLON || (BABYLON = {}));
  79829. //# sourceMappingURL=babylon.boneLookController.js.map
  79830. var BABYLON;
  79831. (function (BABYLON) {
  79832. /**
  79833. * Class used to handle skinning animations
  79834. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79835. */
  79836. var Skeleton = /** @class */ (function () {
  79837. /**
  79838. * Creates a new skeleton
  79839. * @param name defines the skeleton name
  79840. * @param id defines the skeleton Id
  79841. * @param scene defines the hosting scene
  79842. */
  79843. function Skeleton(
  79844. /** defines the skeleton name */
  79845. name,
  79846. /** defines the skeleton Id */
  79847. id, scene) {
  79848. this.name = name;
  79849. this.id = id;
  79850. /**
  79851. * Gets the list of child bones
  79852. */
  79853. this.bones = new Array();
  79854. /**
  79855. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79856. */
  79857. this.needInitialSkinMatrix = false;
  79858. this._isDirty = true;
  79859. this._meshesWithPoseMatrix = new Array();
  79860. this._identity = BABYLON.Matrix.Identity();
  79861. this._ranges = {};
  79862. this._lastAbsoluteTransformsUpdateId = -1;
  79863. /**
  79864. * Specifies if the skeleton should be serialized
  79865. */
  79866. this.doNotSerialize = false;
  79867. this._animationPropertiesOverride = null;
  79868. // Events
  79869. /**
  79870. * An observable triggered before computing the skeleton's matrices
  79871. */
  79872. this.onBeforeComputeObservable = new BABYLON.Observable();
  79873. this.bones = [];
  79874. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79875. scene.skeletons.push(this);
  79876. //make sure it will recalculate the matrix next time prepare is called.
  79877. this._isDirty = true;
  79878. }
  79879. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79880. /**
  79881. * Gets or sets the animation properties override
  79882. */
  79883. get: function () {
  79884. if (!this._animationPropertiesOverride) {
  79885. return this._scene.animationPropertiesOverride;
  79886. }
  79887. return this._animationPropertiesOverride;
  79888. },
  79889. set: function (value) {
  79890. this._animationPropertiesOverride = value;
  79891. },
  79892. enumerable: true,
  79893. configurable: true
  79894. });
  79895. // Members
  79896. /**
  79897. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79898. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79899. * @returns a Float32Array containing matrices data
  79900. */
  79901. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79902. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79903. return mesh._bonesTransformMatrices;
  79904. }
  79905. if (!this._transformMatrices) {
  79906. this.prepare();
  79907. }
  79908. return this._transformMatrices;
  79909. };
  79910. /**
  79911. * Gets the current hosting scene
  79912. * @returns a scene object
  79913. */
  79914. Skeleton.prototype.getScene = function () {
  79915. return this._scene;
  79916. };
  79917. // Methods
  79918. /**
  79919. * Gets a string representing the current skeleton data
  79920. * @param fullDetails defines a boolean indicating if we want a verbose version
  79921. * @returns a string representing the current skeleton data
  79922. */
  79923. Skeleton.prototype.toString = function (fullDetails) {
  79924. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79925. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79926. if (fullDetails) {
  79927. ret += ", Ranges: {";
  79928. var first = true;
  79929. for (var name_1 in this._ranges) {
  79930. if (first) {
  79931. ret += ", ";
  79932. first = false;
  79933. }
  79934. ret += name_1;
  79935. }
  79936. ret += "}";
  79937. }
  79938. return ret;
  79939. };
  79940. /**
  79941. * Get bone's index searching by name
  79942. * @param name defines bone's name to search for
  79943. * @return the indice of the bone. Returns -1 if not found
  79944. */
  79945. Skeleton.prototype.getBoneIndexByName = function (name) {
  79946. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79947. if (this.bones[boneIndex].name === name) {
  79948. return boneIndex;
  79949. }
  79950. }
  79951. return -1;
  79952. };
  79953. /**
  79954. * Creater a new animation range
  79955. * @param name defines the name of the range
  79956. * @param from defines the start key
  79957. * @param to defines the end key
  79958. */
  79959. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79960. // check name not already in use
  79961. if (!this._ranges[name]) {
  79962. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79963. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79964. if (this.bones[i].animations[0]) {
  79965. this.bones[i].animations[0].createRange(name, from, to);
  79966. }
  79967. }
  79968. }
  79969. };
  79970. /**
  79971. * Delete a specific animation range
  79972. * @param name defines the name of the range
  79973. * @param deleteFrames defines if frames must be removed as well
  79974. */
  79975. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79976. if (deleteFrames === void 0) { deleteFrames = true; }
  79977. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79978. if (this.bones[i].animations[0]) {
  79979. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79980. }
  79981. }
  79982. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79983. };
  79984. /**
  79985. * Gets a specific animation range
  79986. * @param name defines the name of the range to look for
  79987. * @returns the requested animation range or null if not found
  79988. */
  79989. Skeleton.prototype.getAnimationRange = function (name) {
  79990. return this._ranges[name];
  79991. };
  79992. /**
  79993. * Gets the list of all animation ranges defined on this skeleton
  79994. * @returns an array
  79995. */
  79996. Skeleton.prototype.getAnimationRanges = function () {
  79997. var animationRanges = [];
  79998. var name;
  79999. var i = 0;
  80000. for (name in this._ranges) {
  80001. animationRanges[i] = this._ranges[name];
  80002. i++;
  80003. }
  80004. return animationRanges;
  80005. };
  80006. /**
  80007. * Copy animation range from a source skeleton.
  80008. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80009. * @param source defines the source skeleton
  80010. * @param name defines the name of the range to copy
  80011. * @param rescaleAsRequired defines if rescaling must be applied if required
  80012. * @returns true if operation was successful
  80013. */
  80014. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80015. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80016. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80017. return false;
  80018. }
  80019. var ret = true;
  80020. var frameOffset = this._getHighestAnimationFrame() + 1;
  80021. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80022. var boneDict = {};
  80023. var sourceBones = source.bones;
  80024. var nBones;
  80025. var i;
  80026. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80027. boneDict[sourceBones[i].name] = sourceBones[i];
  80028. }
  80029. if (this.bones.length !== sourceBones.length) {
  80030. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80031. ret = false;
  80032. }
  80033. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80034. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80035. var boneName = this.bones[i].name;
  80036. var sourceBone = boneDict[boneName];
  80037. if (sourceBone) {
  80038. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80039. }
  80040. else {
  80041. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80042. ret = false;
  80043. }
  80044. }
  80045. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80046. var range = source.getAnimationRange(name);
  80047. if (range) {
  80048. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80049. }
  80050. return ret;
  80051. };
  80052. /**
  80053. * Forces the skeleton to go to rest pose
  80054. */
  80055. Skeleton.prototype.returnToRest = function () {
  80056. for (var index = 0; index < this.bones.length; index++) {
  80057. this.bones[index].returnToRest();
  80058. }
  80059. };
  80060. Skeleton.prototype._getHighestAnimationFrame = function () {
  80061. var ret = 0;
  80062. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80063. if (this.bones[i].animations[0]) {
  80064. var highest = this.bones[i].animations[0].getHighestFrame();
  80065. if (ret < highest) {
  80066. ret = highest;
  80067. }
  80068. }
  80069. }
  80070. return ret;
  80071. };
  80072. /**
  80073. * Begin a specific animation range
  80074. * @param name defines the name of the range to start
  80075. * @param loop defines if looping must be turned on (false by default)
  80076. * @param speedRatio defines the speed ratio to apply (1 by default)
  80077. * @param onAnimationEnd defines a callback which will be called when animation will end
  80078. * @returns a new animatable
  80079. */
  80080. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80081. var range = this.getAnimationRange(name);
  80082. if (!range) {
  80083. return null;
  80084. }
  80085. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80086. };
  80087. /** @hidden */
  80088. Skeleton.prototype._markAsDirty = function () {
  80089. this._isDirty = true;
  80090. };
  80091. /** @hidden */
  80092. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80093. this._meshesWithPoseMatrix.push(mesh);
  80094. };
  80095. /** @hidden */
  80096. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80097. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80098. if (index > -1) {
  80099. this._meshesWithPoseMatrix.splice(index, 1);
  80100. }
  80101. };
  80102. /** @hidden */
  80103. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80104. this.onBeforeComputeObservable.notifyObservers(this);
  80105. for (var index = 0; index < this.bones.length; index++) {
  80106. var bone = this.bones[index];
  80107. var parentBone = bone.getParent();
  80108. if (parentBone) {
  80109. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80110. }
  80111. else {
  80112. if (initialSkinMatrix) {
  80113. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80114. }
  80115. else {
  80116. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80117. }
  80118. }
  80119. if (bone._index !== -1) {
  80120. var mappedIndex = bone._index === null ? index : bone._index;
  80121. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80122. }
  80123. }
  80124. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80125. };
  80126. /**
  80127. * Build all resources required to render a skeleton
  80128. */
  80129. Skeleton.prototype.prepare = function () {
  80130. if (!this._isDirty) {
  80131. return;
  80132. }
  80133. if (this.needInitialSkinMatrix) {
  80134. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80135. var mesh = this._meshesWithPoseMatrix[index];
  80136. var poseMatrix = mesh.getPoseMatrix();
  80137. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80138. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80139. }
  80140. if (this._synchronizedWithMesh !== mesh) {
  80141. this._synchronizedWithMesh = mesh;
  80142. // Prepare bones
  80143. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80144. var bone = this.bones[boneIndex];
  80145. if (!bone.getParent()) {
  80146. var matrix = bone.getBaseMatrix();
  80147. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80148. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80149. }
  80150. }
  80151. }
  80152. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80153. }
  80154. }
  80155. else {
  80156. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80157. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80158. }
  80159. this._computeTransformMatrices(this._transformMatrices, null);
  80160. }
  80161. this._isDirty = false;
  80162. this._scene._activeBones.addCount(this.bones.length, false);
  80163. };
  80164. /**
  80165. * Gets the list of animatables currently running for this skeleton
  80166. * @returns an array of animatables
  80167. */
  80168. Skeleton.prototype.getAnimatables = function () {
  80169. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80170. this._animatables = [];
  80171. for (var index = 0; index < this.bones.length; index++) {
  80172. this._animatables.push(this.bones[index]);
  80173. }
  80174. }
  80175. return this._animatables;
  80176. };
  80177. /**
  80178. * Clone the current skeleton
  80179. * @param name defines the name of the new skeleton
  80180. * @param id defines the id of the enw skeleton
  80181. * @returns the new skeleton
  80182. */
  80183. Skeleton.prototype.clone = function (name, id) {
  80184. var result = new Skeleton(name, id || name, this._scene);
  80185. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80186. for (var index = 0; index < this.bones.length; index++) {
  80187. var source = this.bones[index];
  80188. var parentBone = null;
  80189. var parent_1 = source.getParent();
  80190. if (parent_1) {
  80191. var parentIndex = this.bones.indexOf(parent_1);
  80192. parentBone = result.bones[parentIndex];
  80193. }
  80194. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80195. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80196. }
  80197. if (this._ranges) {
  80198. result._ranges = {};
  80199. for (var rangeName in this._ranges) {
  80200. var range = this._ranges[rangeName];
  80201. if (range) {
  80202. result._ranges[rangeName] = range.clone();
  80203. }
  80204. }
  80205. }
  80206. this._isDirty = true;
  80207. return result;
  80208. };
  80209. /**
  80210. * Enable animation blending for this skeleton
  80211. * @param blendingSpeed defines the blending speed to apply
  80212. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80213. */
  80214. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80215. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80216. this.bones.forEach(function (bone) {
  80217. bone.animations.forEach(function (animation) {
  80218. animation.enableBlending = true;
  80219. animation.blendingSpeed = blendingSpeed;
  80220. });
  80221. });
  80222. };
  80223. /**
  80224. * Releases all resources associated with the current skeleton
  80225. */
  80226. Skeleton.prototype.dispose = function () {
  80227. this._meshesWithPoseMatrix = [];
  80228. // Animations
  80229. this.getScene().stopAnimation(this);
  80230. // Remove from scene
  80231. this.getScene().removeSkeleton(this);
  80232. };
  80233. /**
  80234. * Serialize the skeleton in a JSON object
  80235. * @returns a JSON object
  80236. */
  80237. Skeleton.prototype.serialize = function () {
  80238. var serializationObject = {};
  80239. serializationObject.name = this.name;
  80240. serializationObject.id = this.id;
  80241. if (this.dimensionsAtRest) {
  80242. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80243. }
  80244. serializationObject.bones = [];
  80245. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80246. for (var index = 0; index < this.bones.length; index++) {
  80247. var bone = this.bones[index];
  80248. var parent_2 = bone.getParent();
  80249. var serializedBone = {
  80250. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80251. name: bone.name,
  80252. matrix: bone.getBaseMatrix().toArray(),
  80253. rest: bone.getRestPose().toArray()
  80254. };
  80255. serializationObject.bones.push(serializedBone);
  80256. if (bone.length) {
  80257. serializedBone.length = bone.length;
  80258. }
  80259. if (bone.metadata) {
  80260. serializedBone.metadata = bone.metadata;
  80261. }
  80262. if (bone.animations && bone.animations.length > 0) {
  80263. serializedBone.animation = bone.animations[0].serialize();
  80264. }
  80265. serializationObject.ranges = [];
  80266. for (var name in this._ranges) {
  80267. var source = this._ranges[name];
  80268. if (!source) {
  80269. continue;
  80270. }
  80271. var range = {};
  80272. range.name = name;
  80273. range.from = source.from;
  80274. range.to = source.to;
  80275. serializationObject.ranges.push(range);
  80276. }
  80277. }
  80278. return serializationObject;
  80279. };
  80280. /**
  80281. * Creates a new skeleton from serialized data
  80282. * @param parsedSkeleton defines the serialized data
  80283. * @param scene defines the hosting scene
  80284. * @returns a new skeleton
  80285. */
  80286. Skeleton.Parse = function (parsedSkeleton, scene) {
  80287. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80288. if (parsedSkeleton.dimensionsAtRest) {
  80289. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80290. }
  80291. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80292. var index;
  80293. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80294. var parsedBone = parsedSkeleton.bones[index];
  80295. var parentBone = null;
  80296. if (parsedBone.parentBoneIndex > -1) {
  80297. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80298. }
  80299. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80300. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80301. if (parsedBone.length) {
  80302. bone.length = parsedBone.length;
  80303. }
  80304. if (parsedBone.metadata) {
  80305. bone.metadata = parsedBone.metadata;
  80306. }
  80307. if (parsedBone.animation) {
  80308. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80309. }
  80310. }
  80311. // placed after bones, so createAnimationRange can cascade down
  80312. if (parsedSkeleton.ranges) {
  80313. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80314. var data = parsedSkeleton.ranges[index];
  80315. skeleton.createAnimationRange(data.name, data.from, data.to);
  80316. }
  80317. }
  80318. return skeleton;
  80319. };
  80320. /**
  80321. * Compute all node absolute transforms
  80322. * @param forceUpdate defines if computation must be done even if cache is up to date
  80323. */
  80324. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80325. if (forceUpdate === void 0) { forceUpdate = false; }
  80326. var renderId = this._scene.getRenderId();
  80327. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80328. this.bones[0].computeAbsoluteTransforms();
  80329. this._lastAbsoluteTransformsUpdateId = renderId;
  80330. }
  80331. };
  80332. /**
  80333. * Gets the root pose matrix
  80334. * @returns a matrix
  80335. */
  80336. Skeleton.prototype.getPoseMatrix = function () {
  80337. var poseMatrix = null;
  80338. if (this._meshesWithPoseMatrix.length > 0) {
  80339. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80340. }
  80341. return poseMatrix;
  80342. };
  80343. /**
  80344. * Sorts bones per internal index
  80345. */
  80346. Skeleton.prototype.sortBones = function () {
  80347. var bones = new Array();
  80348. var visited = new Array(this.bones.length);
  80349. for (var index = 0; index < this.bones.length; index++) {
  80350. this._sortBones(index, bones, visited);
  80351. }
  80352. this.bones = bones;
  80353. };
  80354. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80355. if (visited[index]) {
  80356. return;
  80357. }
  80358. visited[index] = true;
  80359. var bone = this.bones[index];
  80360. if (bone._index === undefined) {
  80361. bone._index = index;
  80362. }
  80363. var parentBone = bone.getParent();
  80364. if (parentBone) {
  80365. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80366. }
  80367. bones.push(bone);
  80368. };
  80369. return Skeleton;
  80370. }());
  80371. BABYLON.Skeleton = Skeleton;
  80372. })(BABYLON || (BABYLON = {}));
  80373. //# sourceMappingURL=babylon.skeleton.js.map
  80374. var BABYLON;
  80375. (function (BABYLON) {
  80376. var SphericalPolynomial = /** @class */ (function () {
  80377. function SphericalPolynomial() {
  80378. this.x = BABYLON.Vector3.Zero();
  80379. this.y = BABYLON.Vector3.Zero();
  80380. this.z = BABYLON.Vector3.Zero();
  80381. this.xx = BABYLON.Vector3.Zero();
  80382. this.yy = BABYLON.Vector3.Zero();
  80383. this.zz = BABYLON.Vector3.Zero();
  80384. this.xy = BABYLON.Vector3.Zero();
  80385. this.yz = BABYLON.Vector3.Zero();
  80386. this.zx = BABYLON.Vector3.Zero();
  80387. }
  80388. SphericalPolynomial.prototype.addAmbient = function (color) {
  80389. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80390. this.xx = this.xx.add(colorVector);
  80391. this.yy = this.yy.add(colorVector);
  80392. this.zz = this.zz.add(colorVector);
  80393. };
  80394. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80395. var result = new SphericalPolynomial();
  80396. result.x = harmonics.L11.scale(1.02333);
  80397. result.y = harmonics.L1_1.scale(1.02333);
  80398. result.z = harmonics.L10.scale(1.02333);
  80399. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80400. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80401. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80402. result.yz = harmonics.L2_1.scale(0.858086);
  80403. result.zx = harmonics.L21.scale(0.858086);
  80404. result.xy = harmonics.L2_2.scale(0.858086);
  80405. result.scale(1.0 / Math.PI);
  80406. return result;
  80407. };
  80408. SphericalPolynomial.prototype.scale = function (scale) {
  80409. this.x = this.x.scale(scale);
  80410. this.y = this.y.scale(scale);
  80411. this.z = this.z.scale(scale);
  80412. this.xx = this.xx.scale(scale);
  80413. this.yy = this.yy.scale(scale);
  80414. this.zz = this.zz.scale(scale);
  80415. this.yz = this.yz.scale(scale);
  80416. this.zx = this.zx.scale(scale);
  80417. this.xy = this.xy.scale(scale);
  80418. };
  80419. return SphericalPolynomial;
  80420. }());
  80421. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80422. var SphericalHarmonics = /** @class */ (function () {
  80423. function SphericalHarmonics() {
  80424. this.L00 = BABYLON.Vector3.Zero();
  80425. this.L1_1 = BABYLON.Vector3.Zero();
  80426. this.L10 = BABYLON.Vector3.Zero();
  80427. this.L11 = BABYLON.Vector3.Zero();
  80428. this.L2_2 = BABYLON.Vector3.Zero();
  80429. this.L2_1 = BABYLON.Vector3.Zero();
  80430. this.L20 = BABYLON.Vector3.Zero();
  80431. this.L21 = BABYLON.Vector3.Zero();
  80432. this.L22 = BABYLON.Vector3.Zero();
  80433. }
  80434. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80435. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80436. var c = colorVector.scale(deltaSolidAngle);
  80437. this.L00 = this.L00.add(c.scale(0.282095));
  80438. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80439. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80440. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80441. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80442. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80443. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80444. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80445. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80446. };
  80447. SphericalHarmonics.prototype.scale = function (scale) {
  80448. this.L00 = this.L00.scale(scale);
  80449. this.L1_1 = this.L1_1.scale(scale);
  80450. this.L10 = this.L10.scale(scale);
  80451. this.L11 = this.L11.scale(scale);
  80452. this.L2_2 = this.L2_2.scale(scale);
  80453. this.L2_1 = this.L2_1.scale(scale);
  80454. this.L20 = this.L20.scale(scale);
  80455. this.L21 = this.L21.scale(scale);
  80456. this.L22 = this.L22.scale(scale);
  80457. };
  80458. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80459. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80460. //
  80461. // E_lm = A_l * L_lm
  80462. //
  80463. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80464. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80465. // the scaling factors are given in equation 9.
  80466. // Constant (Band 0)
  80467. this.L00 = this.L00.scale(3.141593);
  80468. // Linear (Band 1)
  80469. this.L1_1 = this.L1_1.scale(2.094395);
  80470. this.L10 = this.L10.scale(2.094395);
  80471. this.L11 = this.L11.scale(2.094395);
  80472. // Quadratic (Band 2)
  80473. this.L2_2 = this.L2_2.scale(0.785398);
  80474. this.L2_1 = this.L2_1.scale(0.785398);
  80475. this.L20 = this.L20.scale(0.785398);
  80476. this.L21 = this.L21.scale(0.785398);
  80477. this.L22 = this.L22.scale(0.785398);
  80478. };
  80479. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80480. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80481. // L = (1/pi) * E * rho
  80482. //
  80483. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80484. this.scale(1.0 / Math.PI);
  80485. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80486. // (The pixel shader must apply albedo after texture fetches, etc).
  80487. };
  80488. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80489. var result = new SphericalHarmonics();
  80490. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80491. result.L1_1 = polynomial.y.scale(0.977204);
  80492. result.L10 = polynomial.z.scale(0.977204);
  80493. result.L11 = polynomial.x.scale(0.977204);
  80494. result.L2_2 = polynomial.xy.scale(1.16538);
  80495. result.L2_1 = polynomial.yz.scale(1.16538);
  80496. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80497. result.L21 = polynomial.zx.scale(1.16538);
  80498. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80499. result.scale(Math.PI);
  80500. return result;
  80501. };
  80502. return SphericalHarmonics;
  80503. }());
  80504. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80505. })(BABYLON || (BABYLON = {}));
  80506. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80507. var BABYLON;
  80508. (function (BABYLON) {
  80509. var FileFaceOrientation = /** @class */ (function () {
  80510. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80511. this.name = name;
  80512. this.worldAxisForNormal = worldAxisForNormal;
  80513. this.worldAxisForFileX = worldAxisForFileX;
  80514. this.worldAxisForFileY = worldAxisForFileY;
  80515. }
  80516. return FileFaceOrientation;
  80517. }());
  80518. ;
  80519. /**
  80520. * Helper class dealing with the extraction of spherical polynomial dataArray
  80521. * from a cube map.
  80522. */
  80523. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80524. function CubeMapToSphericalPolynomialTools() {
  80525. }
  80526. /**
  80527. * Converts a texture to the according Spherical Polynomial data.
  80528. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80529. *
  80530. * @param texture The texture to extract the information from.
  80531. * @return The Spherical Polynomial data.
  80532. */
  80533. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80534. if (!texture.isCube) {
  80535. // Only supports cube Textures currently.
  80536. return null;
  80537. }
  80538. var size = texture.getSize().width;
  80539. var right = texture.readPixels(0);
  80540. var left = texture.readPixels(1);
  80541. var up;
  80542. var down;
  80543. if (texture.isRenderTarget) {
  80544. up = texture.readPixels(3);
  80545. down = texture.readPixels(2);
  80546. }
  80547. else {
  80548. up = texture.readPixels(2);
  80549. down = texture.readPixels(3);
  80550. }
  80551. var front = texture.readPixels(4);
  80552. var back = texture.readPixels(5);
  80553. var gammaSpace = texture.gammaSpace;
  80554. // Always read as RGBA.
  80555. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80556. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80557. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80558. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80559. }
  80560. var cubeInfo = {
  80561. size: size,
  80562. right: right,
  80563. left: left,
  80564. up: up,
  80565. down: down,
  80566. front: front,
  80567. back: back,
  80568. format: format,
  80569. type: type,
  80570. gammaSpace: gammaSpace,
  80571. };
  80572. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80573. };
  80574. /**
  80575. * Converts a cubemap to the according Spherical Polynomial data.
  80576. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80577. *
  80578. * @param cubeInfo The Cube map to extract the information from.
  80579. * @return The Spherical Polynomial data.
  80580. */
  80581. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80582. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80583. var totalSolidAngle = 0.0;
  80584. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80585. var du = 2.0 / cubeInfo.size;
  80586. var dv = du;
  80587. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80588. var minUV = du * 0.5 - 1.0;
  80589. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80590. var fileFace = this.FileFaces[faceIndex];
  80591. var dataArray = cubeInfo[fileFace.name];
  80592. var v = minUV;
  80593. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80594. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80595. // Because SP is still linear, so summation is fine in that basis.
  80596. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80597. for (var y = 0; y < cubeInfo.size; y++) {
  80598. var u = minUV;
  80599. for (var x = 0; x < cubeInfo.size; x++) {
  80600. // World direction (not normalised)
  80601. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80602. worldDirection.normalize();
  80603. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80604. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80605. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80606. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80607. // Handle Integer types.
  80608. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80609. r /= 255;
  80610. g /= 255;
  80611. b /= 255;
  80612. }
  80613. // Handle Gamma space textures.
  80614. if (cubeInfo.gammaSpace) {
  80615. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80616. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80617. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80618. }
  80619. var color = new BABYLON.Color3(r, g, b);
  80620. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80621. totalSolidAngle += deltaSolidAngle;
  80622. u += du;
  80623. }
  80624. v += dv;
  80625. }
  80626. }
  80627. // Solid angle for entire sphere is 4*pi
  80628. var sphereSolidAngle = 4.0 * Math.PI;
  80629. // Adjust the solid angle to allow for how many faces we processed.
  80630. var facesProcessed = 6.0;
  80631. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80632. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80633. // This is needed because the numerical integration over the cube uses a
  80634. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80635. // and also to compensate for accumulative error due to float precision in the summation.
  80636. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80637. sphericalHarmonics.scale(correctionFactor);
  80638. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80639. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80640. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80641. };
  80642. CubeMapToSphericalPolynomialTools.FileFaces = [
  80643. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80644. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80645. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80646. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80647. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80648. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80649. ];
  80650. return CubeMapToSphericalPolynomialTools;
  80651. }());
  80652. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80653. })(BABYLON || (BABYLON = {}));
  80654. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80655. var BABYLON;
  80656. (function (BABYLON) {
  80657. /**
  80658. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80659. */
  80660. var PanoramaToCubeMapTools = /** @class */ (function () {
  80661. function PanoramaToCubeMapTools() {
  80662. }
  80663. /**
  80664. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80665. *
  80666. * @param float32Array The source data.
  80667. * @param inputWidth The width of the input panorama.
  80668. * @param inputhHeight The height of the input panorama.
  80669. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80670. * @return The cubemap data
  80671. */
  80672. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80673. if (!float32Array) {
  80674. throw "ConvertPanoramaToCubemap: input cannot be null";
  80675. }
  80676. if (float32Array.length != inputWidth * inputHeight * 3) {
  80677. throw "ConvertPanoramaToCubemap: input size is wrong";
  80678. }
  80679. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80680. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80681. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80682. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80683. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80684. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80685. return {
  80686. front: textureFront,
  80687. back: textureBack,
  80688. left: textureLeft,
  80689. right: textureRight,
  80690. up: textureUp,
  80691. down: textureDown,
  80692. size: size,
  80693. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80694. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80695. gammaSpace: false,
  80696. };
  80697. };
  80698. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80699. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80700. var textureArray = new Float32Array(buffer);
  80701. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80702. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80703. var dy = 1 / texSize;
  80704. var fy = 0;
  80705. for (var y = 0; y < texSize; y++) {
  80706. var xv1 = faceData[0];
  80707. var xv2 = faceData[2];
  80708. for (var x = 0; x < texSize; x++) {
  80709. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80710. v.normalize();
  80711. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80712. // 3 channels per pixels
  80713. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80714. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80715. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80716. xv1 = xv1.add(rotDX1);
  80717. xv2 = xv2.add(rotDX2);
  80718. }
  80719. fy += dy;
  80720. }
  80721. return textureArray;
  80722. };
  80723. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80724. var theta = Math.atan2(vDir.z, vDir.x);
  80725. var phi = Math.acos(vDir.y);
  80726. while (theta < -Math.PI)
  80727. theta += 2 * Math.PI;
  80728. while (theta > Math.PI)
  80729. theta -= 2 * Math.PI;
  80730. var dx = theta / Math.PI;
  80731. var dy = phi / Math.PI;
  80732. // recenter.
  80733. dx = dx * 0.5 + 0.5;
  80734. var px = Math.round(dx * inputWidth);
  80735. if (px < 0)
  80736. px = 0;
  80737. else if (px >= inputWidth)
  80738. px = inputWidth - 1;
  80739. var py = Math.round(dy * inputHeight);
  80740. if (py < 0)
  80741. py = 0;
  80742. else if (py >= inputHeight)
  80743. py = inputHeight - 1;
  80744. var inputY = (inputHeight - py - 1);
  80745. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80746. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80747. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80748. return {
  80749. r: r,
  80750. g: g,
  80751. b: b
  80752. };
  80753. };
  80754. PanoramaToCubeMapTools.FACE_FRONT = [
  80755. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80756. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80757. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80758. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80759. ];
  80760. PanoramaToCubeMapTools.FACE_BACK = [
  80761. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80762. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80763. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80764. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80765. ];
  80766. PanoramaToCubeMapTools.FACE_RIGHT = [
  80767. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80768. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80769. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80770. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80771. ];
  80772. PanoramaToCubeMapTools.FACE_LEFT = [
  80773. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80774. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80775. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80776. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80777. ];
  80778. PanoramaToCubeMapTools.FACE_DOWN = [
  80779. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80780. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80781. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80782. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80783. ];
  80784. PanoramaToCubeMapTools.FACE_UP = [
  80785. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80786. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80787. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80788. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80789. ];
  80790. return PanoramaToCubeMapTools;
  80791. }());
  80792. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80793. })(BABYLON || (BABYLON = {}));
  80794. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80795. var BABYLON;
  80796. (function (BABYLON) {
  80797. ;
  80798. /**
  80799. * This groups tools to convert HDR texture to native colors array.
  80800. */
  80801. var HDRTools = /** @class */ (function () {
  80802. function HDRTools() {
  80803. }
  80804. HDRTools.Ldexp = function (mantissa, exponent) {
  80805. if (exponent > 1023) {
  80806. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80807. }
  80808. if (exponent < -1074) {
  80809. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80810. }
  80811. return mantissa * Math.pow(2, exponent);
  80812. };
  80813. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80814. if (exponent > 0) { /*nonzero pixel*/
  80815. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80816. float32array[index + 0] = red * exponent;
  80817. float32array[index + 1] = green * exponent;
  80818. float32array[index + 2] = blue * exponent;
  80819. }
  80820. else {
  80821. float32array[index + 0] = 0;
  80822. float32array[index + 1] = 0;
  80823. float32array[index + 2] = 0;
  80824. }
  80825. };
  80826. HDRTools.readStringLine = function (uint8array, startIndex) {
  80827. var line = "";
  80828. var character = "";
  80829. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80830. character = String.fromCharCode(uint8array[i]);
  80831. if (character == "\n") {
  80832. break;
  80833. }
  80834. line += character;
  80835. }
  80836. return line;
  80837. };
  80838. /**
  80839. * Reads header information from an RGBE texture stored in a native array.
  80840. * More information on this format are available here:
  80841. * https://en.wikipedia.org/wiki/RGBE_image_format
  80842. *
  80843. * @param uint8array The binary file stored in native array.
  80844. * @return The header information.
  80845. */
  80846. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80847. var height = 0;
  80848. var width = 0;
  80849. var line = this.readStringLine(uint8array, 0);
  80850. if (line[0] != '#' || line[1] != '?') {
  80851. throw "Bad HDR Format.";
  80852. }
  80853. var endOfHeader = false;
  80854. var findFormat = false;
  80855. var lineIndex = 0;
  80856. do {
  80857. lineIndex += (line.length + 1);
  80858. line = this.readStringLine(uint8array, lineIndex);
  80859. if (line == "FORMAT=32-bit_rle_rgbe") {
  80860. findFormat = true;
  80861. }
  80862. else if (line.length == 0) {
  80863. endOfHeader = true;
  80864. }
  80865. } while (!endOfHeader);
  80866. if (!findFormat) {
  80867. throw "HDR Bad header format, unsupported FORMAT";
  80868. }
  80869. lineIndex += (line.length + 1);
  80870. line = this.readStringLine(uint8array, lineIndex);
  80871. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80872. var match = sizeRegexp.exec(line);
  80873. // TODO. Support +Y and -X if needed.
  80874. if (!match || match.length < 3) {
  80875. throw "HDR Bad header format, no size";
  80876. }
  80877. width = parseInt(match[2]);
  80878. height = parseInt(match[1]);
  80879. if (width < 8 || width > 0x7fff) {
  80880. throw "HDR Bad header format, unsupported size";
  80881. }
  80882. lineIndex += (line.length + 1);
  80883. return {
  80884. height: height,
  80885. width: width,
  80886. dataPosition: lineIndex
  80887. };
  80888. };
  80889. /**
  80890. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80891. * This RGBE texture needs to store the information as a panorama.
  80892. *
  80893. * More information on this format are available here:
  80894. * https://en.wikipedia.org/wiki/RGBE_image_format
  80895. *
  80896. * @param buffer The binary file stored in an array buffer.
  80897. * @param size The expected size of the extracted cubemap.
  80898. * @return The Cube Map information.
  80899. */
  80900. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80901. var uint8array = new Uint8Array(buffer);
  80902. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80903. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80904. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80905. return cubeMapData;
  80906. };
  80907. /**
  80908. * Returns the pixels data extracted from an RGBE texture.
  80909. * This pixels will be stored left to right up to down in the R G B order in one array.
  80910. *
  80911. * More information on this format are available here:
  80912. * https://en.wikipedia.org/wiki/RGBE_image_format
  80913. *
  80914. * @param uint8array The binary file stored in an array buffer.
  80915. * @param hdrInfo The header information of the file.
  80916. * @return The pixels data in RGB right to left up to down order.
  80917. */
  80918. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80919. // Keep for multi format supports.
  80920. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80921. };
  80922. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80923. var num_scanlines = hdrInfo.height;
  80924. var scanline_width = hdrInfo.width;
  80925. var a, b, c, d, count;
  80926. var dataIndex = hdrInfo.dataPosition;
  80927. var index = 0, endIndex = 0, i = 0;
  80928. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80929. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80930. // 3 channels of 4 bytes per pixel in float.
  80931. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80932. var resultArray = new Float32Array(resultBuffer);
  80933. // read in each successive scanline
  80934. while (num_scanlines > 0) {
  80935. a = uint8array[dataIndex++];
  80936. b = uint8array[dataIndex++];
  80937. c = uint8array[dataIndex++];
  80938. d = uint8array[dataIndex++];
  80939. if (a != 2 || b != 2 || (c & 0x80)) {
  80940. // this file is not run length encoded
  80941. throw "HDR Bad header format, not RLE";
  80942. }
  80943. if (((c << 8) | d) != scanline_width) {
  80944. throw "HDR Bad header format, wrong scan line width";
  80945. }
  80946. index = 0;
  80947. // read each of the four channels for the scanline into the buffer
  80948. for (i = 0; i < 4; i++) {
  80949. endIndex = (i + 1) * scanline_width;
  80950. while (index < endIndex) {
  80951. a = uint8array[dataIndex++];
  80952. b = uint8array[dataIndex++];
  80953. if (a > 128) {
  80954. // a run of the same value
  80955. count = a - 128;
  80956. if ((count == 0) || (count > endIndex - index)) {
  80957. throw "HDR Bad Format, bad scanline data (run)";
  80958. }
  80959. while (count-- > 0) {
  80960. scanLineArray[index++] = b;
  80961. }
  80962. }
  80963. else {
  80964. // a non-run
  80965. count = a;
  80966. if ((count == 0) || (count > endIndex - index)) {
  80967. throw "HDR Bad Format, bad scanline data (non-run)";
  80968. }
  80969. scanLineArray[index++] = b;
  80970. if (--count > 0) {
  80971. for (var j = 0; j < count; j++) {
  80972. scanLineArray[index++] = uint8array[dataIndex++];
  80973. }
  80974. }
  80975. }
  80976. }
  80977. }
  80978. // now convert data from buffer into floats
  80979. for (i = 0; i < scanline_width; i++) {
  80980. a = scanLineArray[i];
  80981. b = scanLineArray[i + scanline_width];
  80982. c = scanLineArray[i + 2 * scanline_width];
  80983. d = scanLineArray[i + 3 * scanline_width];
  80984. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80985. }
  80986. num_scanlines--;
  80987. }
  80988. return resultArray;
  80989. };
  80990. return HDRTools;
  80991. }());
  80992. BABYLON.HDRTools = HDRTools;
  80993. })(BABYLON || (BABYLON = {}));
  80994. //# sourceMappingURL=babylon.hdr.js.map
  80995. var BABYLON;
  80996. (function (BABYLON) {
  80997. /**
  80998. * Sets of helpers addressing the serialization and deserialization of environment texture
  80999. * stored in a BabylonJS env file.
  81000. * Those files are usually stored as .env files.
  81001. */
  81002. var EnvironmentTextureTools = /** @class */ (function () {
  81003. function EnvironmentTextureTools() {
  81004. }
  81005. /**
  81006. * Gets the environment info from an env file.
  81007. * @param data The array buffer containing the .env bytes.
  81008. * @returns the environment file info (the json header) if successfully parsed.
  81009. */
  81010. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81011. var dataView = new DataView(data);
  81012. var pos = 0;
  81013. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81014. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81015. BABYLON.Tools.Error('Not a babylon environment map');
  81016. return null;
  81017. }
  81018. }
  81019. // Read json manifest - collect characters up to null terminator
  81020. var manifestString = '';
  81021. var charCode = 0x00;
  81022. while ((charCode = dataView.getUint8(pos++))) {
  81023. manifestString += String.fromCharCode(charCode);
  81024. }
  81025. var manifest = JSON.parse(manifestString);
  81026. if (manifest.specular) {
  81027. // Extend the header with the position of the payload.
  81028. manifest.specular.specularDataPosition = pos;
  81029. }
  81030. return manifest;
  81031. };
  81032. /**
  81033. * Creates an environment texture from a loaded cube texture.
  81034. * @param texture defines the cube texture to convert in env file
  81035. * @return a promise containing the environment data if succesfull.
  81036. */
  81037. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81038. var _this = this;
  81039. var internalTexture = texture.getInternalTexture();
  81040. if (!internalTexture) {
  81041. return Promise.reject("The cube texture is invalid.");
  81042. }
  81043. if (!texture._prefiltered) {
  81044. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81045. }
  81046. var engine = internalTexture.getEngine();
  81047. if (engine && engine.premultipliedAlpha) {
  81048. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option.");
  81049. }
  81050. var canvas = engine.getRenderingCanvas();
  81051. if (!canvas) {
  81052. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81053. }
  81054. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81055. if (!engine.getCaps().textureFloatRender) {
  81056. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81057. if (!engine.getCaps().textureHalfFloatRender) {
  81058. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81059. }
  81060. }
  81061. var cubeWidth = internalTexture.width;
  81062. var hostingScene = new BABYLON.Scene(engine);
  81063. var specularTextures = {};
  81064. var promises = [];
  81065. // Read and collect all mipmaps data from the cube.
  81066. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81067. mipmapsCount = Math.round(mipmapsCount);
  81068. var _loop_1 = function (i) {
  81069. var faceWidth = Math.pow(2, mipmapsCount - i);
  81070. var _loop_2 = function (face) {
  81071. var data = texture.readPixels(face, i);
  81072. // Creates a temp texture with the face data.
  81073. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81074. // And rgbdEncode them.
  81075. var promise = new Promise(function (resolve, reject) {
  81076. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81077. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81078. rgbdPostProcess.onApply = function (effect) {
  81079. effect._bindTexture("textureSampler", tempTexture);
  81080. };
  81081. // As the process needs to happen on the main canvas, keep track of the current size
  81082. var currentW = engine.getRenderWidth();
  81083. var currentH = engine.getRenderHeight();
  81084. // Set the desired size for the texture
  81085. engine.setSize(faceWidth, faceWidth);
  81086. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81087. // Reading datas from WebGL
  81088. canvas.toBlob(function (blob) {
  81089. var fileReader = new FileReader();
  81090. fileReader.onload = function (event) {
  81091. var arrayBuffer = event.target.result;
  81092. specularTextures[i * 6 + face] = arrayBuffer;
  81093. resolve();
  81094. };
  81095. fileReader.readAsArrayBuffer(blob);
  81096. });
  81097. // Reapply the previous canvas size
  81098. engine.setSize(currentW, currentH);
  81099. });
  81100. });
  81101. promises.push(promise);
  81102. };
  81103. // All faces of the cube.
  81104. for (var face = 0; face < 6; face++) {
  81105. _loop_2(face);
  81106. }
  81107. };
  81108. for (var i = 0; i <= mipmapsCount; i++) {
  81109. _loop_1(i);
  81110. }
  81111. // Once all the textures haves been collected as RGBD stored in PNGs
  81112. return Promise.all(promises).then(function () {
  81113. // We can delete the hosting scene keeping track of all the creation objects
  81114. hostingScene.dispose();
  81115. // Creates the json header for the env texture
  81116. var info = {
  81117. version: 1,
  81118. width: cubeWidth,
  81119. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81120. specular: {
  81121. mipmaps: []
  81122. }
  81123. };
  81124. // Sets the specular image data information
  81125. var position = 0;
  81126. for (var i = 0; i <= mipmapsCount; i++) {
  81127. for (var face = 0; face < 6; face++) {
  81128. var byteLength = specularTextures[i * 6 + face].byteLength;
  81129. info.specular.mipmaps.push({
  81130. length: byteLength,
  81131. position: position
  81132. });
  81133. position += byteLength;
  81134. }
  81135. }
  81136. // Encode the JSON as an array buffer
  81137. var infoString = JSON.stringify(info);
  81138. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81139. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81140. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81141. infoView[i] = infoString.charCodeAt(i);
  81142. }
  81143. // Ends up with a null terminator for easier parsing
  81144. infoView[infoString.length] = 0x00;
  81145. // Computes the final required size and creates the storage
  81146. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81147. var finalBuffer = new ArrayBuffer(totalSize);
  81148. var finalBufferView = new Uint8Array(finalBuffer);
  81149. var dataView = new DataView(finalBuffer);
  81150. // Copy the magic bytes identifying the file in
  81151. var pos = 0;
  81152. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81153. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81154. }
  81155. // Add the json info
  81156. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81157. pos += infoBuffer.byteLength;
  81158. // Finally inserts the texture data
  81159. for (var i = 0; i <= mipmapsCount; i++) {
  81160. for (var face = 0; face < 6; face++) {
  81161. var dataBuffer = specularTextures[i * 6 + face];
  81162. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81163. pos += dataBuffer.byteLength;
  81164. }
  81165. }
  81166. // Voila
  81167. return finalBuffer;
  81168. });
  81169. };
  81170. /**
  81171. * Creates a JSON representation of the spherical data.
  81172. * @param texture defines the texture containing the polynomials
  81173. * @return the JSON representation of the spherical info
  81174. */
  81175. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81176. var polynmials = texture.sphericalPolynomial;
  81177. if (polynmials == null) {
  81178. return null;
  81179. }
  81180. return {
  81181. polynomials: true,
  81182. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81183. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81184. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81185. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81186. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81187. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81188. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81189. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81190. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81191. };
  81192. };
  81193. /**
  81194. * Uploads the texture info contained in the env file to te GPU.
  81195. * @param texture defines the internal texture to upload to
  81196. * @param arrayBuffer defines the buffer cotaining the data to load
  81197. * @param info defines the texture info retrieved through the GetEnvInfo method
  81198. * @returns a promise
  81199. */
  81200. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81201. if (info.version !== 1) {
  81202. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81203. }
  81204. var specularInfo = info.specular;
  81205. if (!specularInfo) {
  81206. // Nothing else parsed so far
  81207. return Promise.resolve();
  81208. }
  81209. // Double checks the enclosed info
  81210. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81211. mipmapsCount = Math.round(mipmapsCount) + 1;
  81212. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81213. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81214. }
  81215. // Gets everything ready.
  81216. var engine = texture.getEngine();
  81217. var expandTexture = false;
  81218. var generateNonLODTextures = false;
  81219. var rgbdPostProcess = null;
  81220. var cubeRtt = null;
  81221. var lodTextures = null;
  81222. var caps = engine.getCaps();
  81223. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81224. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81225. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81226. // Add extra process if texture lod is not supported
  81227. if (!caps.textureLOD) {
  81228. expandTexture = false;
  81229. generateNonLODTextures = true;
  81230. lodTextures = {};
  81231. }
  81232. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81233. else if (engine.webGLVersion < 2) {
  81234. expandTexture = false;
  81235. }
  81236. // If half float available we can uncompress the texture
  81237. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81238. expandTexture = true;
  81239. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81240. }
  81241. // If full float available we can uncompress the texture
  81242. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81243. expandTexture = true;
  81244. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81245. }
  81246. // Expand the texture if possible
  81247. if (expandTexture) {
  81248. // Simply run through the decode PP
  81249. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81250. texture._isRGBD = false;
  81251. texture.invertY = false;
  81252. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81253. generateDepthBuffer: false,
  81254. generateMipMaps: true,
  81255. generateStencilBuffer: false,
  81256. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81257. type: texture.type,
  81258. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81259. });
  81260. }
  81261. else {
  81262. texture._isRGBD = true;
  81263. texture.invertY = true;
  81264. // In case of missing support, applies the same patch than DDS files.
  81265. if (generateNonLODTextures) {
  81266. var mipSlices = 3;
  81267. var scale = texture._lodGenerationScale;
  81268. var offset = texture._lodGenerationOffset;
  81269. for (var i = 0; i < mipSlices; i++) {
  81270. //compute LOD from even spacing in smoothness (matching shader calculation)
  81271. var smoothness = i / (mipSlices - 1);
  81272. var roughness = 1 - smoothness;
  81273. var minLODIndex = offset; // roughness = 0
  81274. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81275. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81276. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81277. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81278. glTextureFromLod.isCube = true;
  81279. glTextureFromLod.invertY = true;
  81280. glTextureFromLod.generateMipMaps = false;
  81281. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81282. // Wrap in a base texture for easy binding.
  81283. var lodTexture = new BABYLON.BaseTexture(null);
  81284. lodTexture.isCube = true;
  81285. lodTexture._texture = glTextureFromLod;
  81286. lodTextures[mipmapIndex] = lodTexture;
  81287. switch (i) {
  81288. case 0:
  81289. texture._lodTextureLow = lodTexture;
  81290. break;
  81291. case 1:
  81292. texture._lodTextureMid = lodTexture;
  81293. break;
  81294. case 2:
  81295. texture._lodTextureHigh = lodTexture;
  81296. break;
  81297. }
  81298. }
  81299. }
  81300. }
  81301. var promises = [];
  81302. var _loop_3 = function (i) {
  81303. var _loop_4 = function (face) {
  81304. // Retrieves the face data
  81305. var imageData = specularInfo.mipmaps[i * 6 + face];
  81306. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81307. // Constructs an image element from bytes
  81308. var blob = new Blob([bytes], { type: 'image/png' });
  81309. var url = URL.createObjectURL(blob);
  81310. var image = new Image();
  81311. image.src = url;
  81312. // Enqueue promise to upload to the texture.
  81313. var promise = new Promise(function (resolve, reject) {
  81314. ;
  81315. image.onload = function () {
  81316. if (expandTexture) {
  81317. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81318. reject(message);
  81319. }, image);
  81320. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81321. // Uncompress the data to a RTT
  81322. rgbdPostProcess.onApply = function (effect) {
  81323. effect._bindTexture("textureSampler", tempTexture_1);
  81324. effect.setFloat2("scale", 1, 1);
  81325. };
  81326. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81327. // Cleanup
  81328. engine.restoreDefaultFramebuffer();
  81329. tempTexture_1.dispose();
  81330. window.URL.revokeObjectURL(url);
  81331. resolve();
  81332. });
  81333. }
  81334. else {
  81335. engine._uploadImageToTexture(texture, face, i, image);
  81336. // Upload the face to the none lod texture support
  81337. if (generateNonLODTextures) {
  81338. var lodTexture = lodTextures[i];
  81339. if (lodTexture) {
  81340. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81341. }
  81342. }
  81343. resolve();
  81344. }
  81345. };
  81346. image.onerror = function (error) {
  81347. reject(error);
  81348. };
  81349. });
  81350. promises.push(promise);
  81351. };
  81352. // All faces
  81353. for (var face = 0; face < 6; face++) {
  81354. _loop_4(face);
  81355. }
  81356. };
  81357. // All mipmaps
  81358. for (var i = 0; i < mipmapsCount; i++) {
  81359. _loop_3(i);
  81360. }
  81361. // Once all done, finishes the cleanup and return
  81362. return Promise.all(promises).then(function () {
  81363. // Relase temp RTT.
  81364. if (cubeRtt) {
  81365. engine._releaseFramebufferObjects(cubeRtt);
  81366. cubeRtt._swapAndDie(texture);
  81367. }
  81368. // Relase temp Post Process.
  81369. if (rgbdPostProcess) {
  81370. rgbdPostProcess.dispose();
  81371. }
  81372. // Flag internal texture as ready in case they are in use.
  81373. if (generateNonLODTextures) {
  81374. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81375. texture._lodTextureHigh._texture.isReady = true;
  81376. }
  81377. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81378. texture._lodTextureMid._texture.isReady = true;
  81379. }
  81380. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81381. texture._lodTextureLow._texture.isReady = true;
  81382. }
  81383. }
  81384. });
  81385. };
  81386. /**
  81387. * Uploads spherical polynomials information to the texture.
  81388. * @param texture defines the texture we are trying to upload the information to
  81389. * @param arrayBuffer defines the array buffer holding the data
  81390. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81391. */
  81392. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81393. if (info.version !== 1) {
  81394. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81395. }
  81396. var irradianceInfo = info.irradiance;
  81397. if (!irradianceInfo) {
  81398. return;
  81399. }
  81400. //harmonics now represent radiance
  81401. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81402. if (irradianceInfo.polynomials) {
  81403. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81404. }
  81405. else {
  81406. // convert From SH to SP.
  81407. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81408. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81409. }
  81410. };
  81411. /**
  81412. * Upload spherical polynomial coefficients to the texture
  81413. * @param polynmials Spherical polynmial coefficients (9)
  81414. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81415. */
  81416. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81417. outPolynomialCoefficents.x.x = polynmials.x[0];
  81418. outPolynomialCoefficents.x.y = polynmials.x[1];
  81419. outPolynomialCoefficents.x.z = polynmials.x[2];
  81420. outPolynomialCoefficents.y.x = polynmials.y[0];
  81421. outPolynomialCoefficents.y.y = polynmials.y[1];
  81422. outPolynomialCoefficents.y.z = polynmials.y[2];
  81423. outPolynomialCoefficents.z.x = polynmials.z[0];
  81424. outPolynomialCoefficents.z.y = polynmials.z[1];
  81425. outPolynomialCoefficents.z.z = polynmials.z[2];
  81426. //xx
  81427. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81428. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81429. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81430. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81431. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81432. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81433. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81434. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81435. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81436. //yz
  81437. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81438. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81439. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81440. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81441. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81442. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81443. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81444. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81445. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81446. };
  81447. /**
  81448. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81449. * L = (1/pi) * E * rho
  81450. *
  81451. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81452. * @param harmonics Spherical harmonic coefficients (9)
  81453. */
  81454. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81455. var scaleFactor = 1 / Math.PI;
  81456. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81457. // (The pixel shader must apply albedo after texture fetches, etc).
  81458. harmonics.l00[0] *= scaleFactor;
  81459. harmonics.l00[1] *= scaleFactor;
  81460. harmonics.l00[2] *= scaleFactor;
  81461. harmonics.l1_1[0] *= scaleFactor;
  81462. harmonics.l1_1[1] *= scaleFactor;
  81463. harmonics.l1_1[2] *= scaleFactor;
  81464. harmonics.l10[0] *= scaleFactor;
  81465. harmonics.l10[1] *= scaleFactor;
  81466. harmonics.l10[2] *= scaleFactor;
  81467. harmonics.l11[0] *= scaleFactor;
  81468. harmonics.l11[1] *= scaleFactor;
  81469. harmonics.l11[2] *= scaleFactor;
  81470. harmonics.l2_2[0] *= scaleFactor;
  81471. harmonics.l2_2[1] *= scaleFactor;
  81472. harmonics.l2_2[2] *= scaleFactor;
  81473. harmonics.l2_1[0] *= scaleFactor;
  81474. harmonics.l2_1[1] *= scaleFactor;
  81475. harmonics.l2_1[2] *= scaleFactor;
  81476. harmonics.l20[0] *= scaleFactor;
  81477. harmonics.l20[1] *= scaleFactor;
  81478. harmonics.l20[2] *= scaleFactor;
  81479. harmonics.l21[0] *= scaleFactor;
  81480. harmonics.l21[1] *= scaleFactor;
  81481. harmonics.l21[2] *= scaleFactor;
  81482. harmonics.l22[0] *= scaleFactor;
  81483. harmonics.l22[1] *= scaleFactor;
  81484. harmonics.l22[2] *= scaleFactor;
  81485. };
  81486. /**
  81487. * Convert spherical harmonics to spherical polynomial coefficients
  81488. * @param harmonics Spherical harmonic coefficients (9)
  81489. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81490. */
  81491. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81492. var rPi = 1 / Math.PI;
  81493. //x
  81494. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81495. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81496. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81497. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81498. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81499. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81500. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81501. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81502. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81503. //xx
  81504. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81505. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81506. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81507. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81508. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81509. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81510. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81511. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81512. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81513. //yz
  81514. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81515. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81516. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81517. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81518. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81519. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81520. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81521. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81522. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81523. };
  81524. /**
  81525. * Magic number identifying the env file.
  81526. */
  81527. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81528. return EnvironmentTextureTools;
  81529. }());
  81530. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81531. })(BABYLON || (BABYLON = {}));
  81532. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81533. var BABYLON;
  81534. (function (BABYLON) {
  81535. /**
  81536. * This represents a texture coming from an HDR input.
  81537. *
  81538. * The only supported format is currently panorama picture stored in RGBE format.
  81539. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81540. */
  81541. var HDRCubeTexture = /** @class */ (function (_super) {
  81542. __extends(HDRCubeTexture, _super);
  81543. /**
  81544. * Instantiates an HDRTexture from the following parameters.
  81545. *
  81546. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81547. * @param scene The scene the texture will be used in
  81548. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81549. * @param noMipmap Forces to not generate the mipmap if true
  81550. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81551. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  81552. * @param reserved Reserved flag for internal use.
  81553. */
  81554. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81555. if (noMipmap === void 0) { noMipmap = false; }
  81556. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81557. if (gammaSpace === void 0) { gammaSpace = false; }
  81558. if (reserved === void 0) { reserved = false; }
  81559. if (onLoad === void 0) { onLoad = null; }
  81560. if (onError === void 0) { onError = null; }
  81561. var _this = _super.call(this, scene) || this;
  81562. _this._generateHarmonics = true;
  81563. _this._onLoad = null;
  81564. _this._onError = null;
  81565. /**
  81566. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81567. */
  81568. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81569. _this._isBlocking = true;
  81570. _this._rotationY = 0;
  81571. /**
  81572. * Gets or sets the center of the bounding box associated with the cube texture
  81573. * It must define where the camera used to render the texture was set
  81574. */
  81575. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81576. if (!url) {
  81577. return _this;
  81578. }
  81579. _this.name = url;
  81580. _this.url = url;
  81581. _this.hasAlpha = false;
  81582. _this.isCube = true;
  81583. _this._textureMatrix = BABYLON.Matrix.Identity();
  81584. _this._onLoad = onLoad;
  81585. _this._onError = onError;
  81586. _this.gammaSpace = gammaSpace;
  81587. _this._noMipmap = noMipmap;
  81588. _this._size = size;
  81589. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81590. if (!_this._texture) {
  81591. if (!scene.useDelayedTextureLoading) {
  81592. _this.loadTexture();
  81593. }
  81594. else {
  81595. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81596. }
  81597. }
  81598. return _this;
  81599. }
  81600. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81601. /**
  81602. * Gets wether or not the texture is blocking during loading.
  81603. */
  81604. get: function () {
  81605. return this._isBlocking;
  81606. },
  81607. /**
  81608. * Sets wether or not the texture is blocking during loading.
  81609. */
  81610. set: function (value) {
  81611. this._isBlocking = value;
  81612. },
  81613. enumerable: true,
  81614. configurable: true
  81615. });
  81616. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81617. /**
  81618. * Gets texture matrix rotation angle around Y axis radians.
  81619. */
  81620. get: function () {
  81621. return this._rotationY;
  81622. },
  81623. /**
  81624. * Sets texture matrix rotation angle around Y axis in radians.
  81625. */
  81626. set: function (value) {
  81627. this._rotationY = value;
  81628. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81629. },
  81630. enumerable: true,
  81631. configurable: true
  81632. });
  81633. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81634. get: function () {
  81635. return this._boundingBoxSize;
  81636. },
  81637. /**
  81638. * Gets or sets the size of the bounding box associated with the cube texture
  81639. * When defined, the cubemap will switch to local mode
  81640. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81641. * @example https://www.babylonjs-playground.com/#RNASML
  81642. */
  81643. set: function (value) {
  81644. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81645. return;
  81646. }
  81647. this._boundingBoxSize = value;
  81648. var scene = this.getScene();
  81649. if (scene) {
  81650. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81651. }
  81652. },
  81653. enumerable: true,
  81654. configurable: true
  81655. });
  81656. /**
  81657. * Occurs when the file is raw .hdr file.
  81658. */
  81659. HDRCubeTexture.prototype.loadTexture = function () {
  81660. var _this = this;
  81661. var callback = function (buffer) {
  81662. var scene = _this.getScene();
  81663. if (!scene) {
  81664. return null;
  81665. }
  81666. // Extract the raw linear data.
  81667. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81668. // Generate harmonics if needed.
  81669. if (_this._generateHarmonics) {
  81670. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81671. _this.sphericalPolynomial = sphericalPolynomial;
  81672. }
  81673. var results = [];
  81674. var byteArray = null;
  81675. // Push each faces.
  81676. for (var j = 0; j < 6; j++) {
  81677. // Create uintarray fallback.
  81678. if (!scene.getEngine().getCaps().textureFloat) {
  81679. // 3 channels of 1 bytes per pixel in bytes.
  81680. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81681. byteArray = new Uint8Array(byteBuffer);
  81682. }
  81683. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81684. // If special cases.
  81685. if (_this.gammaSpace || byteArray) {
  81686. for (var i = 0; i < _this._size * _this._size; i++) {
  81687. // Put in gamma space if requested.
  81688. if (_this.gammaSpace) {
  81689. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81690. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81691. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81692. }
  81693. // Convert to int texture for fallback.
  81694. if (byteArray) {
  81695. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81696. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81697. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81698. // May use luminance instead if the result is not accurate.
  81699. var max = Math.max(Math.max(r, g), b);
  81700. if (max > 255) {
  81701. var scale = 255 / max;
  81702. r *= scale;
  81703. g *= scale;
  81704. b *= scale;
  81705. }
  81706. byteArray[(i * 3) + 0] = r;
  81707. byteArray[(i * 3) + 1] = g;
  81708. byteArray[(i * 3) + 2] = b;
  81709. }
  81710. }
  81711. }
  81712. if (byteArray) {
  81713. results.push(byteArray);
  81714. }
  81715. else {
  81716. results.push(dataFace);
  81717. }
  81718. }
  81719. return results;
  81720. };
  81721. var scene = this.getScene();
  81722. if (scene) {
  81723. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  81724. }
  81725. };
  81726. HDRCubeTexture.prototype.clone = function () {
  81727. var scene = this.getScene();
  81728. if (!scene) {
  81729. return this;
  81730. }
  81731. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81732. // Base texture
  81733. newTexture.level = this.level;
  81734. newTexture.wrapU = this.wrapU;
  81735. newTexture.wrapV = this.wrapV;
  81736. newTexture.coordinatesIndex = this.coordinatesIndex;
  81737. newTexture.coordinatesMode = this.coordinatesMode;
  81738. return newTexture;
  81739. };
  81740. // Methods
  81741. HDRCubeTexture.prototype.delayLoad = function () {
  81742. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81743. return;
  81744. }
  81745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81746. this._texture = this._getFromCache(this.url, this._noMipmap);
  81747. if (!this._texture) {
  81748. this.loadTexture();
  81749. }
  81750. };
  81751. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81752. return this._textureMatrix;
  81753. };
  81754. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81755. this._textureMatrix = value;
  81756. };
  81757. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81758. var texture = null;
  81759. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81760. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81761. texture.name = parsedTexture.name;
  81762. texture.hasAlpha = parsedTexture.hasAlpha;
  81763. texture.level = parsedTexture.level;
  81764. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81765. texture.isBlocking = parsedTexture.isBlocking;
  81766. }
  81767. if (texture) {
  81768. if (parsedTexture.boundingBoxPosition) {
  81769. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81770. }
  81771. if (parsedTexture.boundingBoxSize) {
  81772. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81773. }
  81774. if (parsedTexture.rotationY) {
  81775. texture.rotationY = parsedTexture.rotationY;
  81776. }
  81777. }
  81778. return texture;
  81779. };
  81780. HDRCubeTexture.prototype.serialize = function () {
  81781. if (!this.name) {
  81782. return null;
  81783. }
  81784. var serializationObject = {};
  81785. serializationObject.name = this.name;
  81786. serializationObject.hasAlpha = this.hasAlpha;
  81787. serializationObject.isCube = true;
  81788. serializationObject.level = this.level;
  81789. serializationObject.size = this._size;
  81790. serializationObject.coordinatesMode = this.coordinatesMode;
  81791. serializationObject.useInGammaSpace = this.gammaSpace;
  81792. serializationObject.generateHarmonics = this._generateHarmonics;
  81793. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81794. serializationObject.noMipmap = this._noMipmap;
  81795. serializationObject.isBlocking = this._isBlocking;
  81796. serializationObject.rotationY = this._rotationY;
  81797. return serializationObject;
  81798. };
  81799. HDRCubeTexture._facesMapping = [
  81800. "right",
  81801. "left",
  81802. "up",
  81803. "down",
  81804. "front",
  81805. "back"
  81806. ];
  81807. return HDRCubeTexture;
  81808. }(BABYLON.BaseTexture));
  81809. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81810. })(BABYLON || (BABYLON = {}));
  81811. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81812. var BABYLON;
  81813. (function (BABYLON) {
  81814. var IndexedVector2 = /** @class */ (function (_super) {
  81815. __extends(IndexedVector2, _super);
  81816. function IndexedVector2(original, index) {
  81817. var _this = _super.call(this, original.x, original.y) || this;
  81818. _this.index = index;
  81819. return _this;
  81820. }
  81821. return IndexedVector2;
  81822. }(BABYLON.Vector2));
  81823. var PolygonPoints = /** @class */ (function () {
  81824. function PolygonPoints() {
  81825. this.elements = new Array();
  81826. }
  81827. PolygonPoints.prototype.add = function (originalPoints) {
  81828. var _this = this;
  81829. var result = new Array();
  81830. originalPoints.forEach(function (point) {
  81831. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81832. var newPoint = new IndexedVector2(point, _this.elements.length);
  81833. result.push(newPoint);
  81834. _this.elements.push(newPoint);
  81835. }
  81836. });
  81837. return result;
  81838. };
  81839. PolygonPoints.prototype.computeBounds = function () {
  81840. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81841. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81842. this.elements.forEach(function (point) {
  81843. // x
  81844. if (point.x < lmin.x) {
  81845. lmin.x = point.x;
  81846. }
  81847. else if (point.x > lmax.x) {
  81848. lmax.x = point.x;
  81849. }
  81850. // y
  81851. if (point.y < lmin.y) {
  81852. lmin.y = point.y;
  81853. }
  81854. else if (point.y > lmax.y) {
  81855. lmax.y = point.y;
  81856. }
  81857. });
  81858. return {
  81859. min: lmin,
  81860. max: lmax,
  81861. width: lmax.x - lmin.x,
  81862. height: lmax.y - lmin.y
  81863. };
  81864. };
  81865. return PolygonPoints;
  81866. }());
  81867. var Polygon = /** @class */ (function () {
  81868. function Polygon() {
  81869. }
  81870. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81871. return [
  81872. new BABYLON.Vector2(xmin, ymin),
  81873. new BABYLON.Vector2(xmax, ymin),
  81874. new BABYLON.Vector2(xmax, ymax),
  81875. new BABYLON.Vector2(xmin, ymax)
  81876. ];
  81877. };
  81878. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81879. if (cx === void 0) { cx = 0; }
  81880. if (cy === void 0) { cy = 0; }
  81881. if (numberOfSides === void 0) { numberOfSides = 32; }
  81882. var result = new Array();
  81883. var angle = 0;
  81884. var increment = (Math.PI * 2) / numberOfSides;
  81885. for (var i = 0; i < numberOfSides; i++) {
  81886. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81887. angle -= increment;
  81888. }
  81889. return result;
  81890. };
  81891. Polygon.Parse = function (input) {
  81892. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81893. var i, result = [];
  81894. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81895. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81896. }
  81897. return result;
  81898. };
  81899. Polygon.StartingAt = function (x, y) {
  81900. return BABYLON.Path2.StartingAt(x, y);
  81901. };
  81902. return Polygon;
  81903. }());
  81904. BABYLON.Polygon = Polygon;
  81905. var PolygonMeshBuilder = /** @class */ (function () {
  81906. function PolygonMeshBuilder(name, contours, scene) {
  81907. this._points = new PolygonPoints();
  81908. this._outlinepoints = new PolygonPoints();
  81909. this._holes = new Array();
  81910. this._epoints = new Array();
  81911. this._eholes = new Array();
  81912. this._name = name;
  81913. this._scene = scene;
  81914. var points;
  81915. if (contours instanceof BABYLON.Path2) {
  81916. points = contours.getPoints();
  81917. }
  81918. else {
  81919. points = contours;
  81920. }
  81921. this._addToepoint(points);
  81922. this._points.add(points);
  81923. this._outlinepoints.add(points);
  81924. if (typeof earcut === 'undefined') {
  81925. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81926. }
  81927. }
  81928. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81929. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81930. var p = points_1[_i];
  81931. this._epoints.push(p.x, p.y);
  81932. }
  81933. };
  81934. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81935. this._points.add(hole);
  81936. var holepoints = new PolygonPoints();
  81937. holepoints.add(hole);
  81938. this._holes.push(holepoints);
  81939. this._eholes.push(this._epoints.length / 2);
  81940. this._addToepoint(hole);
  81941. return this;
  81942. };
  81943. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81944. var _this = this;
  81945. if (updatable === void 0) { updatable = false; }
  81946. if (depth === void 0) { depth = 0; }
  81947. var result = new BABYLON.Mesh(this._name, this._scene);
  81948. var normals = new Array();
  81949. var positions = new Array();
  81950. var uvs = new Array();
  81951. var bounds = this._points.computeBounds();
  81952. this._points.elements.forEach(function (p) {
  81953. normals.push(0, 1.0, 0);
  81954. positions.push(p.x, 0, p.y);
  81955. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81956. });
  81957. var indices = new Array();
  81958. var res = earcut(this._epoints, this._eholes, 2);
  81959. for (var i = 0; i < res.length; i++) {
  81960. indices.push(res[i]);
  81961. }
  81962. if (depth > 0) {
  81963. var positionscount = (positions.length / 3); //get the current pointcount
  81964. this._points.elements.forEach(function (p) {
  81965. normals.push(0, -1.0, 0);
  81966. positions.push(p.x, -depth, p.y);
  81967. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81968. });
  81969. var totalCount = indices.length;
  81970. for (var i = 0; i < totalCount; i += 3) {
  81971. var i0 = indices[i + 0];
  81972. var i1 = indices[i + 1];
  81973. var i2 = indices[i + 2];
  81974. indices.push(i2 + positionscount);
  81975. indices.push(i1 + positionscount);
  81976. indices.push(i0 + positionscount);
  81977. }
  81978. //Add the sides
  81979. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81980. this._holes.forEach(function (hole) {
  81981. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81982. });
  81983. }
  81984. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81985. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81986. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81987. result.setIndices(indices);
  81988. return result;
  81989. };
  81990. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81991. var StartIndex = positions.length / 3;
  81992. var ulength = 0;
  81993. for (var i = 0; i < points.elements.length; i++) {
  81994. var p = points.elements[i];
  81995. var p1;
  81996. if ((i + 1) > points.elements.length - 1) {
  81997. p1 = points.elements[0];
  81998. }
  81999. else {
  82000. p1 = points.elements[i + 1];
  82001. }
  82002. positions.push(p.x, 0, p.y);
  82003. positions.push(p.x, -depth, p.y);
  82004. positions.push(p1.x, 0, p1.y);
  82005. positions.push(p1.x, -depth, p1.y);
  82006. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82007. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82008. var v3 = v2.subtract(v1);
  82009. var v4 = new BABYLON.Vector3(0, 1, 0);
  82010. var vn = BABYLON.Vector3.Cross(v3, v4);
  82011. vn = vn.normalize();
  82012. uvs.push(ulength / bounds.width, 0);
  82013. uvs.push(ulength / bounds.width, 1);
  82014. ulength += v3.length();
  82015. uvs.push((ulength / bounds.width), 0);
  82016. uvs.push((ulength / bounds.width), 1);
  82017. if (!flip) {
  82018. normals.push(-vn.x, -vn.y, -vn.z);
  82019. normals.push(-vn.x, -vn.y, -vn.z);
  82020. normals.push(-vn.x, -vn.y, -vn.z);
  82021. normals.push(-vn.x, -vn.y, -vn.z);
  82022. indices.push(StartIndex);
  82023. indices.push(StartIndex + 1);
  82024. indices.push(StartIndex + 2);
  82025. indices.push(StartIndex + 1);
  82026. indices.push(StartIndex + 3);
  82027. indices.push(StartIndex + 2);
  82028. }
  82029. else {
  82030. normals.push(vn.x, vn.y, vn.z);
  82031. normals.push(vn.x, vn.y, vn.z);
  82032. normals.push(vn.x, vn.y, vn.z);
  82033. normals.push(vn.x, vn.y, vn.z);
  82034. indices.push(StartIndex);
  82035. indices.push(StartIndex + 2);
  82036. indices.push(StartIndex + 1);
  82037. indices.push(StartIndex + 1);
  82038. indices.push(StartIndex + 2);
  82039. indices.push(StartIndex + 3);
  82040. }
  82041. StartIndex += 4;
  82042. }
  82043. ;
  82044. };
  82045. return PolygonMeshBuilder;
  82046. }());
  82047. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82048. })(BABYLON || (BABYLON = {}));
  82049. //# sourceMappingURL=babylon.polygonMesh.js.map
  82050. var BABYLON;
  82051. (function (BABYLON) {
  82052. // Unique ID when we import meshes from Babylon to CSG
  82053. var currentCSGMeshId = 0;
  82054. // # class Vertex
  82055. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82056. // one to provide additional features like texture coordinates and vertex
  82057. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82058. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82059. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82060. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82061. // is not used anywhere else.
  82062. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82063. var Vertex = /** @class */ (function () {
  82064. function Vertex(pos, normal, uv) {
  82065. this.pos = pos;
  82066. this.normal = normal;
  82067. this.uv = uv;
  82068. }
  82069. Vertex.prototype.clone = function () {
  82070. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82071. };
  82072. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82073. // orientation of a polygon is flipped.
  82074. Vertex.prototype.flip = function () {
  82075. this.normal = this.normal.scale(-1);
  82076. };
  82077. // Create a new vertex between this vertex and `other` by linearly
  82078. // interpolating all properties using a parameter of `t`. Subclasses should
  82079. // override this to interpolate additional properties.
  82080. Vertex.prototype.interpolate = function (other, t) {
  82081. 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));
  82082. };
  82083. return Vertex;
  82084. }());
  82085. // # class Plane
  82086. // Represents a plane in 3D space.
  82087. var Plane = /** @class */ (function () {
  82088. function Plane(normal, w) {
  82089. this.normal = normal;
  82090. this.w = w;
  82091. }
  82092. Plane.FromPoints = function (a, b, c) {
  82093. var v0 = c.subtract(a);
  82094. var v1 = b.subtract(a);
  82095. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82096. return null;
  82097. }
  82098. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82099. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82100. };
  82101. Plane.prototype.clone = function () {
  82102. return new Plane(this.normal.clone(), this.w);
  82103. };
  82104. Plane.prototype.flip = function () {
  82105. this.normal.scaleInPlace(-1);
  82106. this.w = -this.w;
  82107. };
  82108. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82109. // fragments in the appropriate lists. Coplanar polygons go into either
  82110. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82111. // respect to this plane. Polygons in front or in back of this plane go into
  82112. // either `front` or `back`.
  82113. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82114. var COPLANAR = 0;
  82115. var FRONT = 1;
  82116. var BACK = 2;
  82117. var SPANNING = 3;
  82118. // Classify each point as well as the entire polygon into one of the above
  82119. // four classes.
  82120. var polygonType = 0;
  82121. var types = [];
  82122. var i;
  82123. var t;
  82124. for (i = 0; i < polygon.vertices.length; i++) {
  82125. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82126. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82127. polygonType |= type;
  82128. types.push(type);
  82129. }
  82130. // Put the polygon in the correct list, splitting it when necessary.
  82131. switch (polygonType) {
  82132. case COPLANAR:
  82133. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82134. break;
  82135. case FRONT:
  82136. front.push(polygon);
  82137. break;
  82138. case BACK:
  82139. back.push(polygon);
  82140. break;
  82141. case SPANNING:
  82142. var f = [], b = [];
  82143. for (i = 0; i < polygon.vertices.length; i++) {
  82144. var j = (i + 1) % polygon.vertices.length;
  82145. var ti = types[i], tj = types[j];
  82146. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82147. if (ti !== BACK)
  82148. f.push(vi);
  82149. if (ti !== FRONT)
  82150. b.push(ti !== BACK ? vi.clone() : vi);
  82151. if ((ti | tj) === SPANNING) {
  82152. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82153. var v = vi.interpolate(vj, t);
  82154. f.push(v);
  82155. b.push(v.clone());
  82156. }
  82157. }
  82158. var poly;
  82159. if (f.length >= 3) {
  82160. poly = new Polygon(f, polygon.shared);
  82161. if (poly.plane)
  82162. front.push(poly);
  82163. }
  82164. if (b.length >= 3) {
  82165. poly = new Polygon(b, polygon.shared);
  82166. if (poly.plane)
  82167. back.push(poly);
  82168. }
  82169. break;
  82170. }
  82171. };
  82172. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82173. // point is on the plane.
  82174. Plane.EPSILON = 1e-5;
  82175. return Plane;
  82176. }());
  82177. // # class Polygon
  82178. // Represents a convex polygon. The vertices used to initialize a polygon must
  82179. // be coplanar and form a convex loop.
  82180. //
  82181. // Each convex polygon has a `shared` property, which is shared between all
  82182. // polygons that are clones of each other or were split from the same polygon.
  82183. // This can be used to define per-polygon properties (such as surface color).
  82184. var Polygon = /** @class */ (function () {
  82185. function Polygon(vertices, shared) {
  82186. this.vertices = vertices;
  82187. this.shared = shared;
  82188. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82189. }
  82190. Polygon.prototype.clone = function () {
  82191. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82192. return new Polygon(vertices, this.shared);
  82193. };
  82194. Polygon.prototype.flip = function () {
  82195. this.vertices.reverse().map(function (v) { v.flip(); });
  82196. this.plane.flip();
  82197. };
  82198. return Polygon;
  82199. }());
  82200. // # class Node
  82201. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82202. // by picking a polygon to split along. That polygon (and all other coplanar
  82203. // polygons) are added directly to that node and the other polygons are added to
  82204. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82205. // no distinction between internal and leaf nodes.
  82206. var Node = /** @class */ (function () {
  82207. function Node(polygons) {
  82208. this.plane = null;
  82209. this.front = null;
  82210. this.back = null;
  82211. this.polygons = new Array();
  82212. if (polygons) {
  82213. this.build(polygons);
  82214. }
  82215. }
  82216. Node.prototype.clone = function () {
  82217. var node = new Node();
  82218. node.plane = this.plane && this.plane.clone();
  82219. node.front = this.front && this.front.clone();
  82220. node.back = this.back && this.back.clone();
  82221. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82222. return node;
  82223. };
  82224. // Convert solid space to empty space and empty space to solid space.
  82225. Node.prototype.invert = function () {
  82226. for (var i = 0; i < this.polygons.length; i++) {
  82227. this.polygons[i].flip();
  82228. }
  82229. if (this.plane) {
  82230. this.plane.flip();
  82231. }
  82232. if (this.front) {
  82233. this.front.invert();
  82234. }
  82235. if (this.back) {
  82236. this.back.invert();
  82237. }
  82238. var temp = this.front;
  82239. this.front = this.back;
  82240. this.back = temp;
  82241. };
  82242. // Recursively remove all polygons in `polygons` that are inside this BSP
  82243. // tree.
  82244. Node.prototype.clipPolygons = function (polygons) {
  82245. if (!this.plane)
  82246. return polygons.slice();
  82247. var front = new Array(), back = new Array();
  82248. for (var i = 0; i < polygons.length; i++) {
  82249. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82250. }
  82251. if (this.front) {
  82252. front = this.front.clipPolygons(front);
  82253. }
  82254. if (this.back) {
  82255. back = this.back.clipPolygons(back);
  82256. }
  82257. else {
  82258. back = [];
  82259. }
  82260. return front.concat(back);
  82261. };
  82262. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82263. // `bsp`.
  82264. Node.prototype.clipTo = function (bsp) {
  82265. this.polygons = bsp.clipPolygons(this.polygons);
  82266. if (this.front)
  82267. this.front.clipTo(bsp);
  82268. if (this.back)
  82269. this.back.clipTo(bsp);
  82270. };
  82271. // Return a list of all polygons in this BSP tree.
  82272. Node.prototype.allPolygons = function () {
  82273. var polygons = this.polygons.slice();
  82274. if (this.front)
  82275. polygons = polygons.concat(this.front.allPolygons());
  82276. if (this.back)
  82277. polygons = polygons.concat(this.back.allPolygons());
  82278. return polygons;
  82279. };
  82280. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82281. // new polygons are filtered down to the bottom of the tree and become new
  82282. // nodes there. Each set of polygons is partitioned using the first polygon
  82283. // (no heuristic is used to pick a good split).
  82284. Node.prototype.build = function (polygons) {
  82285. if (!polygons.length)
  82286. return;
  82287. if (!this.plane)
  82288. this.plane = polygons[0].plane.clone();
  82289. var front = new Array(), back = new Array();
  82290. for (var i = 0; i < polygons.length; i++) {
  82291. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82292. }
  82293. if (front.length) {
  82294. if (!this.front)
  82295. this.front = new Node();
  82296. this.front.build(front);
  82297. }
  82298. if (back.length) {
  82299. if (!this.back)
  82300. this.back = new Node();
  82301. this.back.build(back);
  82302. }
  82303. };
  82304. return Node;
  82305. }());
  82306. var CSG = /** @class */ (function () {
  82307. function CSG() {
  82308. this.polygons = new Array();
  82309. }
  82310. // Convert BABYLON.Mesh to BABYLON.CSG
  82311. CSG.FromMesh = function (mesh) {
  82312. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82313. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82314. if (mesh instanceof BABYLON.Mesh) {
  82315. mesh.computeWorldMatrix(true);
  82316. matrix = mesh.getWorldMatrix();
  82317. meshPosition = mesh.position.clone();
  82318. meshRotation = mesh.rotation.clone();
  82319. if (mesh.rotationQuaternion) {
  82320. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82321. }
  82322. meshScaling = mesh.scaling.clone();
  82323. }
  82324. else {
  82325. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82326. }
  82327. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82328. var subMeshes = mesh.subMeshes;
  82329. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82330. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82331. vertices = [];
  82332. for (var j = 0; j < 3; j++) {
  82333. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82334. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82335. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82336. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82337. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82338. vertex = new Vertex(position, normal, uv);
  82339. vertices.push(vertex);
  82340. }
  82341. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82342. // To handle the case of degenerated triangle
  82343. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82344. if (polygon.plane)
  82345. polygons.push(polygon);
  82346. }
  82347. }
  82348. var csg = CSG.FromPolygons(polygons);
  82349. csg.matrix = matrix;
  82350. csg.position = meshPosition;
  82351. csg.rotation = meshRotation;
  82352. csg.scaling = meshScaling;
  82353. csg.rotationQuaternion = meshRotationQuaternion;
  82354. currentCSGMeshId++;
  82355. return csg;
  82356. };
  82357. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82358. CSG.FromPolygons = function (polygons) {
  82359. var csg = new CSG();
  82360. csg.polygons = polygons;
  82361. return csg;
  82362. };
  82363. CSG.prototype.clone = function () {
  82364. var csg = new CSG();
  82365. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82366. csg.copyTransformAttributes(this);
  82367. return csg;
  82368. };
  82369. CSG.prototype.union = function (csg) {
  82370. var a = new Node(this.clone().polygons);
  82371. var b = new Node(csg.clone().polygons);
  82372. a.clipTo(b);
  82373. b.clipTo(a);
  82374. b.invert();
  82375. b.clipTo(a);
  82376. b.invert();
  82377. a.build(b.allPolygons());
  82378. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82379. };
  82380. CSG.prototype.unionInPlace = function (csg) {
  82381. var a = new Node(this.polygons);
  82382. var b = new Node(csg.polygons);
  82383. a.clipTo(b);
  82384. b.clipTo(a);
  82385. b.invert();
  82386. b.clipTo(a);
  82387. b.invert();
  82388. a.build(b.allPolygons());
  82389. this.polygons = a.allPolygons();
  82390. };
  82391. CSG.prototype.subtract = function (csg) {
  82392. var a = new Node(this.clone().polygons);
  82393. var b = new Node(csg.clone().polygons);
  82394. a.invert();
  82395. a.clipTo(b);
  82396. b.clipTo(a);
  82397. b.invert();
  82398. b.clipTo(a);
  82399. b.invert();
  82400. a.build(b.allPolygons());
  82401. a.invert();
  82402. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82403. };
  82404. CSG.prototype.subtractInPlace = function (csg) {
  82405. var a = new Node(this.polygons);
  82406. var b = new Node(csg.polygons);
  82407. a.invert();
  82408. a.clipTo(b);
  82409. b.clipTo(a);
  82410. b.invert();
  82411. b.clipTo(a);
  82412. b.invert();
  82413. a.build(b.allPolygons());
  82414. a.invert();
  82415. this.polygons = a.allPolygons();
  82416. };
  82417. CSG.prototype.intersect = function (csg) {
  82418. var a = new Node(this.clone().polygons);
  82419. var b = new Node(csg.clone().polygons);
  82420. a.invert();
  82421. b.clipTo(a);
  82422. b.invert();
  82423. a.clipTo(b);
  82424. b.clipTo(a);
  82425. a.build(b.allPolygons());
  82426. a.invert();
  82427. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82428. };
  82429. CSG.prototype.intersectInPlace = function (csg) {
  82430. var a = new Node(this.polygons);
  82431. var b = new Node(csg.polygons);
  82432. a.invert();
  82433. b.clipTo(a);
  82434. b.invert();
  82435. a.clipTo(b);
  82436. b.clipTo(a);
  82437. a.build(b.allPolygons());
  82438. a.invert();
  82439. this.polygons = a.allPolygons();
  82440. };
  82441. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82442. // not modified.
  82443. CSG.prototype.inverse = function () {
  82444. var csg = this.clone();
  82445. csg.inverseInPlace();
  82446. return csg;
  82447. };
  82448. CSG.prototype.inverseInPlace = function () {
  82449. this.polygons.map(function (p) { p.flip(); });
  82450. };
  82451. // This is used to keep meshes transformations so they can be restored
  82452. // when we build back a Babylon Mesh
  82453. // NB : All CSG operations are performed in world coordinates
  82454. CSG.prototype.copyTransformAttributes = function (csg) {
  82455. this.matrix = csg.matrix;
  82456. this.position = csg.position;
  82457. this.rotation = csg.rotation;
  82458. this.scaling = csg.scaling;
  82459. this.rotationQuaternion = csg.rotationQuaternion;
  82460. return this;
  82461. };
  82462. // Build Raw mesh from CSG
  82463. // Coordinates here are in world space
  82464. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82465. var matrix = this.matrix.clone();
  82466. matrix.invert();
  82467. 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;
  82468. if (keepSubMeshes) {
  82469. // Sort Polygons, since subMeshes are indices range
  82470. polygons.sort(function (a, b) {
  82471. if (a.shared.meshId === b.shared.meshId) {
  82472. return a.shared.subMeshId - b.shared.subMeshId;
  82473. }
  82474. else {
  82475. return a.shared.meshId - b.shared.meshId;
  82476. }
  82477. });
  82478. }
  82479. for (var i = 0, il = polygons.length; i < il; i++) {
  82480. polygon = polygons[i];
  82481. // Building SubMeshes
  82482. if (!subMesh_dict[polygon.shared.meshId]) {
  82483. subMesh_dict[polygon.shared.meshId] = {};
  82484. }
  82485. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82486. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82487. indexStart: +Infinity,
  82488. indexEnd: -Infinity,
  82489. materialIndex: polygon.shared.materialIndex
  82490. };
  82491. }
  82492. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82493. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82494. polygonIndices[0] = 0;
  82495. polygonIndices[1] = j - 1;
  82496. polygonIndices[2] = j;
  82497. for (var k = 0; k < 3; k++) {
  82498. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82499. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82500. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82501. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82502. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82503. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82504. // Check if 2 points can be merged
  82505. if (!(typeof vertex_idx !== 'undefined' &&
  82506. normals[vertex_idx * 3] === localNormal.x &&
  82507. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82508. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82509. uvs[vertex_idx * 2] === uv.x &&
  82510. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82511. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82512. uvs.push(uv.x, uv.y);
  82513. normals.push(normal.x, normal.y, normal.z);
  82514. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82515. }
  82516. indices.push(vertex_idx);
  82517. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82518. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82519. currentIndex++;
  82520. }
  82521. }
  82522. }
  82523. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82524. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82525. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82526. mesh.setIndices(indices, null);
  82527. if (keepSubMeshes) {
  82528. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82529. var materialIndexOffset = 0, materialMaxIndex;
  82530. mesh.subMeshes = new Array();
  82531. for (var m in subMesh_dict) {
  82532. materialMaxIndex = -1;
  82533. for (var sm in subMesh_dict[m]) {
  82534. subMesh_obj = subMesh_dict[m][sm];
  82535. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82536. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82537. }
  82538. materialIndexOffset += ++materialMaxIndex;
  82539. }
  82540. }
  82541. return mesh;
  82542. };
  82543. // Build Mesh from CSG taking material and transforms into account
  82544. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82545. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82546. mesh.material = material;
  82547. mesh.position.copyFrom(this.position);
  82548. mesh.rotation.copyFrom(this.rotation);
  82549. if (this.rotationQuaternion) {
  82550. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82551. }
  82552. mesh.scaling.copyFrom(this.scaling);
  82553. mesh.computeWorldMatrix(true);
  82554. return mesh;
  82555. };
  82556. return CSG;
  82557. }());
  82558. BABYLON.CSG = CSG;
  82559. })(BABYLON || (BABYLON = {}));
  82560. //# sourceMappingURL=babylon.csg.js.map
  82561. var BABYLON;
  82562. (function (BABYLON) {
  82563. var LensFlare = /** @class */ (function () {
  82564. function LensFlare(size, position, color, imgUrl, system) {
  82565. this.size = size;
  82566. this.position = position;
  82567. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82568. this.color = color || new BABYLON.Color3(1, 1, 1);
  82569. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82570. this._system = system;
  82571. system.lensFlares.push(this);
  82572. }
  82573. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82574. return new LensFlare(size, position, color, imgUrl, system);
  82575. };
  82576. LensFlare.prototype.dispose = function () {
  82577. if (this.texture) {
  82578. this.texture.dispose();
  82579. }
  82580. // Remove from scene
  82581. var index = this._system.lensFlares.indexOf(this);
  82582. this._system.lensFlares.splice(index, 1);
  82583. };
  82584. ;
  82585. return LensFlare;
  82586. }());
  82587. BABYLON.LensFlare = LensFlare;
  82588. })(BABYLON || (BABYLON = {}));
  82589. //# sourceMappingURL=babylon.lensFlare.js.map
  82590. var BABYLON;
  82591. (function (BABYLON) {
  82592. var LensFlareSystem = /** @class */ (function () {
  82593. function LensFlareSystem(name, emitter, scene) {
  82594. this.name = name;
  82595. this.lensFlares = new Array();
  82596. this.borderLimit = 300;
  82597. this.viewportBorder = 0;
  82598. this.layerMask = 0x0FFFFFFF;
  82599. this._vertexBuffers = {};
  82600. this._isEnabled = true;
  82601. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82602. this._emitter = emitter;
  82603. this.id = name;
  82604. scene.lensFlareSystems.push(this);
  82605. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82606. var engine = scene.getEngine();
  82607. // VBO
  82608. var vertices = [];
  82609. vertices.push(1, 1);
  82610. vertices.push(-1, 1);
  82611. vertices.push(-1, -1);
  82612. vertices.push(1, -1);
  82613. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82614. // Indices
  82615. var indices = [];
  82616. indices.push(0);
  82617. indices.push(1);
  82618. indices.push(2);
  82619. indices.push(0);
  82620. indices.push(2);
  82621. indices.push(3);
  82622. this._indexBuffer = engine.createIndexBuffer(indices);
  82623. // Effects
  82624. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82625. }
  82626. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82627. get: function () {
  82628. return this._isEnabled;
  82629. },
  82630. set: function (value) {
  82631. this._isEnabled = value;
  82632. },
  82633. enumerable: true,
  82634. configurable: true
  82635. });
  82636. LensFlareSystem.prototype.getScene = function () {
  82637. return this._scene;
  82638. };
  82639. LensFlareSystem.prototype.getEmitter = function () {
  82640. return this._emitter;
  82641. };
  82642. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82643. this._emitter = newEmitter;
  82644. };
  82645. LensFlareSystem.prototype.getEmitterPosition = function () {
  82646. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82647. };
  82648. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82649. var position = this.getEmitterPosition();
  82650. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82651. this._positionX = position.x;
  82652. this._positionY = position.y;
  82653. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82654. if (this.viewportBorder > 0) {
  82655. globalViewport.x -= this.viewportBorder;
  82656. globalViewport.y -= this.viewportBorder;
  82657. globalViewport.width += this.viewportBorder * 2;
  82658. globalViewport.height += this.viewportBorder * 2;
  82659. position.x += this.viewportBorder;
  82660. position.y += this.viewportBorder;
  82661. this._positionX += this.viewportBorder;
  82662. this._positionY += this.viewportBorder;
  82663. }
  82664. if (position.z > 0) {
  82665. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82666. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82667. return true;
  82668. }
  82669. return true;
  82670. }
  82671. return false;
  82672. };
  82673. LensFlareSystem.prototype._isVisible = function () {
  82674. if (!this._isEnabled || !this._scene.activeCamera) {
  82675. return false;
  82676. }
  82677. var emitterPosition = this.getEmitterPosition();
  82678. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82679. var distance = direction.length();
  82680. direction.normalize();
  82681. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82682. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82683. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82684. };
  82685. LensFlareSystem.prototype.render = function () {
  82686. if (!this._effect.isReady() || !this._scene.activeCamera)
  82687. return false;
  82688. var engine = this._scene.getEngine();
  82689. var viewport = this._scene.activeCamera.viewport;
  82690. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82691. // Position
  82692. if (!this.computeEffectivePosition(globalViewport)) {
  82693. return false;
  82694. }
  82695. // Visibility
  82696. if (!this._isVisible()) {
  82697. return false;
  82698. }
  82699. // Intensity
  82700. var awayX;
  82701. var awayY;
  82702. if (this._positionX < this.borderLimit + globalViewport.x) {
  82703. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82704. }
  82705. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82706. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82707. }
  82708. else {
  82709. awayX = 0;
  82710. }
  82711. if (this._positionY < this.borderLimit + globalViewport.y) {
  82712. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82713. }
  82714. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82715. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82716. }
  82717. else {
  82718. awayY = 0;
  82719. }
  82720. var away = (awayX > awayY) ? awayX : awayY;
  82721. away -= this.viewportBorder;
  82722. if (away > this.borderLimit) {
  82723. away = this.borderLimit;
  82724. }
  82725. var intensity = 1.0 - (away / this.borderLimit);
  82726. if (intensity < 0) {
  82727. return false;
  82728. }
  82729. if (intensity > 1.0) {
  82730. intensity = 1.0;
  82731. }
  82732. if (this.viewportBorder > 0) {
  82733. globalViewport.x += this.viewportBorder;
  82734. globalViewport.y += this.viewportBorder;
  82735. globalViewport.width -= this.viewportBorder * 2;
  82736. globalViewport.height -= this.viewportBorder * 2;
  82737. this._positionX -= this.viewportBorder;
  82738. this._positionY -= this.viewportBorder;
  82739. }
  82740. // Position
  82741. var centerX = globalViewport.x + globalViewport.width / 2;
  82742. var centerY = globalViewport.y + globalViewport.height / 2;
  82743. var distX = centerX - this._positionX;
  82744. var distY = centerY - this._positionY;
  82745. // Effects
  82746. engine.enableEffect(this._effect);
  82747. engine.setState(false);
  82748. engine.setDepthBuffer(false);
  82749. // VBOs
  82750. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82751. // Flares
  82752. for (var index = 0; index < this.lensFlares.length; index++) {
  82753. var flare = this.lensFlares[index];
  82754. engine.setAlphaMode(flare.alphaMode);
  82755. var x = centerX - (distX * flare.position);
  82756. var y = centerY - (distY * flare.position);
  82757. var cw = flare.size;
  82758. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82759. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82760. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82761. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82762. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82763. // Texture
  82764. this._effect.setTexture("textureSampler", flare.texture);
  82765. // Color
  82766. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82767. // Draw order
  82768. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82769. }
  82770. engine.setDepthBuffer(true);
  82771. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82772. return true;
  82773. };
  82774. LensFlareSystem.prototype.dispose = function () {
  82775. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82776. if (vertexBuffer) {
  82777. vertexBuffer.dispose();
  82778. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82779. }
  82780. if (this._indexBuffer) {
  82781. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82782. this._indexBuffer = null;
  82783. }
  82784. while (this.lensFlares.length) {
  82785. this.lensFlares[0].dispose();
  82786. }
  82787. // Remove from scene
  82788. var index = this._scene.lensFlareSystems.indexOf(this);
  82789. this._scene.lensFlareSystems.splice(index, 1);
  82790. };
  82791. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82792. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82793. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82794. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82795. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82796. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82797. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82798. var parsedFlare = parsedLensFlareSystem.flares[index];
  82799. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82800. }
  82801. return lensFlareSystem;
  82802. };
  82803. LensFlareSystem.prototype.serialize = function () {
  82804. var serializationObject = {};
  82805. serializationObject.id = this.id;
  82806. serializationObject.name = this.name;
  82807. serializationObject.emitterId = this.getEmitter().id;
  82808. serializationObject.borderLimit = this.borderLimit;
  82809. serializationObject.flares = [];
  82810. for (var index = 0; index < this.lensFlares.length; index++) {
  82811. var flare = this.lensFlares[index];
  82812. serializationObject.flares.push({
  82813. size: flare.size,
  82814. position: flare.position,
  82815. color: flare.color.asArray(),
  82816. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82817. });
  82818. }
  82819. return serializationObject;
  82820. };
  82821. return LensFlareSystem;
  82822. }());
  82823. BABYLON.LensFlareSystem = LensFlareSystem;
  82824. })(BABYLON || (BABYLON = {}));
  82825. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82826. var BABYLON;
  82827. (function (BABYLON) {
  82828. /**
  82829. * This is a holder class for the physics joint created by the physics plugin.
  82830. * It holds a set of functions to control the underlying joint.
  82831. */
  82832. var PhysicsJoint = /** @class */ (function () {
  82833. function PhysicsJoint(type, jointData) {
  82834. this.type = type;
  82835. this.jointData = jointData;
  82836. jointData.nativeParams = jointData.nativeParams || {};
  82837. }
  82838. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82839. get: function () {
  82840. return this._physicsJoint;
  82841. },
  82842. set: function (newJoint) {
  82843. if (this._physicsJoint) {
  82844. //remove from the wolrd
  82845. }
  82846. this._physicsJoint = newJoint;
  82847. },
  82848. enumerable: true,
  82849. configurable: true
  82850. });
  82851. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82852. set: function (physicsPlugin) {
  82853. this._physicsPlugin = physicsPlugin;
  82854. },
  82855. enumerable: true,
  82856. configurable: true
  82857. });
  82858. /**
  82859. * Execute a function that is physics-plugin specific.
  82860. * @param {Function} func the function that will be executed.
  82861. * It accepts two parameters: the physics world and the physics joint.
  82862. */
  82863. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82864. func(this._physicsPlugin.world, this._physicsJoint);
  82865. };
  82866. //TODO check if the native joints are the same
  82867. //Joint Types
  82868. PhysicsJoint.DistanceJoint = 0;
  82869. PhysicsJoint.HingeJoint = 1;
  82870. PhysicsJoint.BallAndSocketJoint = 2;
  82871. PhysicsJoint.WheelJoint = 3;
  82872. PhysicsJoint.SliderJoint = 4;
  82873. //OIMO
  82874. PhysicsJoint.PrismaticJoint = 5;
  82875. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82876. PhysicsJoint.UniversalJoint = 6;
  82877. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82878. //Cannon
  82879. //Similar to a Ball-Joint. Different in params
  82880. PhysicsJoint.PointToPointJoint = 8;
  82881. //Cannon only at the moment
  82882. PhysicsJoint.SpringJoint = 9;
  82883. PhysicsJoint.LockJoint = 10;
  82884. return PhysicsJoint;
  82885. }());
  82886. BABYLON.PhysicsJoint = PhysicsJoint;
  82887. /**
  82888. * A class representing a physics distance joint.
  82889. */
  82890. var DistanceJoint = /** @class */ (function (_super) {
  82891. __extends(DistanceJoint, _super);
  82892. function DistanceJoint(jointData) {
  82893. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82894. }
  82895. /**
  82896. * Update the predefined distance.
  82897. */
  82898. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82899. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82900. };
  82901. return DistanceJoint;
  82902. }(PhysicsJoint));
  82903. BABYLON.DistanceJoint = DistanceJoint;
  82904. var MotorEnabledJoint = /** @class */ (function (_super) {
  82905. __extends(MotorEnabledJoint, _super);
  82906. function MotorEnabledJoint(type, jointData) {
  82907. return _super.call(this, type, jointData) || this;
  82908. }
  82909. /**
  82910. * Set the motor values.
  82911. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82912. * @param {number} force the force to apply
  82913. * @param {number} maxForce max force for this motor.
  82914. */
  82915. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82916. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82917. };
  82918. /**
  82919. * Set the motor's limits.
  82920. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82921. */
  82922. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82923. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82924. };
  82925. return MotorEnabledJoint;
  82926. }(PhysicsJoint));
  82927. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82928. /**
  82929. * This class represents a single hinge physics joint
  82930. */
  82931. var HingeJoint = /** @class */ (function (_super) {
  82932. __extends(HingeJoint, _super);
  82933. function HingeJoint(jointData) {
  82934. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82935. }
  82936. /**
  82937. * Set the motor values.
  82938. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82939. * @param {number} force the force to apply
  82940. * @param {number} maxForce max force for this motor.
  82941. */
  82942. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82943. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82944. };
  82945. /**
  82946. * Set the motor's limits.
  82947. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82948. */
  82949. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82950. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82951. };
  82952. return HingeJoint;
  82953. }(MotorEnabledJoint));
  82954. BABYLON.HingeJoint = HingeJoint;
  82955. /**
  82956. * This class represents a dual hinge physics joint (same as wheel joint)
  82957. */
  82958. var Hinge2Joint = /** @class */ (function (_super) {
  82959. __extends(Hinge2Joint, _super);
  82960. function Hinge2Joint(jointData) {
  82961. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82962. }
  82963. /**
  82964. * Set the motor values.
  82965. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82966. * @param {number} force the force to apply
  82967. * @param {number} maxForce max force for this motor.
  82968. * @param {motorIndex} the motor's index, 0 or 1.
  82969. */
  82970. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82971. if (motorIndex === void 0) { motorIndex = 0; }
  82972. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82973. };
  82974. /**
  82975. * Set the motor limits.
  82976. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82977. * @param {number} upperLimit the upper limit
  82978. * @param {number} lowerLimit lower limit
  82979. * @param {motorIndex} the motor's index, 0 or 1.
  82980. */
  82981. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82982. if (motorIndex === void 0) { motorIndex = 0; }
  82983. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82984. };
  82985. return Hinge2Joint;
  82986. }(MotorEnabledJoint));
  82987. BABYLON.Hinge2Joint = Hinge2Joint;
  82988. })(BABYLON || (BABYLON = {}));
  82989. //# sourceMappingURL=babylon.physicsJoint.js.map
  82990. var BABYLON;
  82991. (function (BABYLON) {
  82992. var PhysicsImpostor = /** @class */ (function () {
  82993. function PhysicsImpostor(object, type, _options, _scene) {
  82994. if (_options === void 0) { _options = { mass: 0 }; }
  82995. var _this = this;
  82996. this.object = object;
  82997. this.type = type;
  82998. this._options = _options;
  82999. this._scene = _scene;
  83000. this._bodyUpdateRequired = false;
  83001. this._onBeforePhysicsStepCallbacks = new Array();
  83002. this._onAfterPhysicsStepCallbacks = new Array();
  83003. this._onPhysicsCollideCallbacks = [];
  83004. this._deltaPosition = BABYLON.Vector3.Zero();
  83005. this._isDisposed = false;
  83006. //temp variables for parent rotation calculations
  83007. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83008. this._tmpQuat = new BABYLON.Quaternion();
  83009. this._tmpQuat2 = new BABYLON.Quaternion();
  83010. /**
  83011. * this function is executed by the physics engine.
  83012. */
  83013. this.beforeStep = function () {
  83014. if (!_this._physicsEngine) {
  83015. return;
  83016. }
  83017. _this.object.translate(_this._deltaPosition, -1);
  83018. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83019. _this.object.computeWorldMatrix(false);
  83020. if (_this.object.parent && _this.object.rotationQuaternion) {
  83021. _this.getParentsRotation();
  83022. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83023. }
  83024. else {
  83025. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83026. }
  83027. if (!_this._options.disableBidirectionalTransformation) {
  83028. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83029. }
  83030. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83031. func(_this);
  83032. });
  83033. };
  83034. /**
  83035. * this function is executed by the physics engine.
  83036. */
  83037. this.afterStep = function () {
  83038. if (!_this._physicsEngine) {
  83039. return;
  83040. }
  83041. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83042. func(_this);
  83043. });
  83044. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83045. // object has now its world rotation. needs to be converted to local.
  83046. if (_this.object.parent && _this.object.rotationQuaternion) {
  83047. _this.getParentsRotation();
  83048. _this._tmpQuat.conjugateInPlace();
  83049. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83050. }
  83051. // take the position set and make it the absolute position of this object.
  83052. _this.object.setAbsolutePosition(_this.object.position);
  83053. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83054. _this.object.translate(_this._deltaPosition, 1);
  83055. };
  83056. /**
  83057. * Legacy collision detection event support
  83058. */
  83059. this.onCollideEvent = null;
  83060. //event and body object due to cannon's event-based architecture.
  83061. this.onCollide = function (e) {
  83062. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83063. return;
  83064. }
  83065. if (!_this._physicsEngine) {
  83066. return;
  83067. }
  83068. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83069. if (otherImpostor) {
  83070. // Legacy collision detection event support
  83071. if (_this.onCollideEvent) {
  83072. _this.onCollideEvent(_this, otherImpostor);
  83073. }
  83074. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83075. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83076. }).forEach(function (obj) {
  83077. obj.callback(_this, otherImpostor);
  83078. });
  83079. }
  83080. };
  83081. //sanity check!
  83082. if (!this.object) {
  83083. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83084. return;
  83085. }
  83086. //legacy support for old syntax.
  83087. if (!this._scene && object.getScene) {
  83088. this._scene = object.getScene();
  83089. }
  83090. if (!this._scene) {
  83091. return;
  83092. }
  83093. this._physicsEngine = this._scene.getPhysicsEngine();
  83094. if (!this._physicsEngine) {
  83095. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83096. }
  83097. else {
  83098. //set the object's quaternion, if not set
  83099. if (!this.object.rotationQuaternion) {
  83100. if (this.object.rotation) {
  83101. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83102. }
  83103. else {
  83104. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83105. }
  83106. }
  83107. //default options params
  83108. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83109. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83110. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83111. this._joints = [];
  83112. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83113. if (!this.object.parent || this._options.ignoreParent) {
  83114. this._init();
  83115. }
  83116. else if (this.object.parent.physicsImpostor) {
  83117. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83118. }
  83119. }
  83120. }
  83121. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83122. get: function () {
  83123. return this._isDisposed;
  83124. },
  83125. enumerable: true,
  83126. configurable: true
  83127. });
  83128. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83129. get: function () {
  83130. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83131. },
  83132. set: function (value) {
  83133. this.setMass(value);
  83134. },
  83135. enumerable: true,
  83136. configurable: true
  83137. });
  83138. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83139. get: function () {
  83140. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83141. },
  83142. set: function (value) {
  83143. if (!this._physicsEngine) {
  83144. return;
  83145. }
  83146. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83147. },
  83148. enumerable: true,
  83149. configurable: true
  83150. });
  83151. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83152. get: function () {
  83153. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83154. },
  83155. set: function (value) {
  83156. if (!this._physicsEngine) {
  83157. return;
  83158. }
  83159. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83160. },
  83161. enumerable: true,
  83162. configurable: true
  83163. });
  83164. /**
  83165. * This function will completly initialize this impostor.
  83166. * It will create a new body - but only if this mesh has no parent.
  83167. * If it has, this impostor will not be used other than to define the impostor
  83168. * of the child mesh.
  83169. */
  83170. PhysicsImpostor.prototype._init = function () {
  83171. if (!this._physicsEngine) {
  83172. return;
  83173. }
  83174. this._physicsEngine.removeImpostor(this);
  83175. this.physicsBody = null;
  83176. this._parent = this._parent || this._getPhysicsParent();
  83177. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83178. this._physicsEngine.addImpostor(this);
  83179. }
  83180. };
  83181. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83182. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83183. var parentMesh = this.object.parent;
  83184. return parentMesh.physicsImpostor;
  83185. }
  83186. return null;
  83187. };
  83188. /**
  83189. * Should a new body be generated.
  83190. */
  83191. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83192. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83193. };
  83194. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83195. this.forceUpdate();
  83196. };
  83197. /**
  83198. * Force a regeneration of this or the parent's impostor's body.
  83199. * Use under cautious - This will remove all joints already implemented.
  83200. */
  83201. PhysicsImpostor.prototype.forceUpdate = function () {
  83202. this._init();
  83203. if (this.parent && !this._options.ignoreParent) {
  83204. this.parent.forceUpdate();
  83205. }
  83206. };
  83207. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83208. /*public get mesh(): AbstractMesh {
  83209. return this._mesh;
  83210. }*/
  83211. /**
  83212. * Gets the body that holds this impostor. Either its own, or its parent.
  83213. */
  83214. get: function () {
  83215. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83216. },
  83217. /**
  83218. * Set the physics body. Used mainly by the physics engine/plugin
  83219. */
  83220. set: function (physicsBody) {
  83221. if (this._physicsBody && this._physicsEngine) {
  83222. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83223. }
  83224. this._physicsBody = physicsBody;
  83225. this.resetUpdateFlags();
  83226. },
  83227. enumerable: true,
  83228. configurable: true
  83229. });
  83230. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83231. get: function () {
  83232. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83233. },
  83234. set: function (value) {
  83235. this._parent = value;
  83236. },
  83237. enumerable: true,
  83238. configurable: true
  83239. });
  83240. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83241. this._bodyUpdateRequired = false;
  83242. };
  83243. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83244. if (this.object.getBoundingInfo) {
  83245. var q = this.object.rotationQuaternion;
  83246. //reset rotation
  83247. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83248. //calculate the world matrix with no rotation
  83249. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83250. var boundingInfo = this.object.getBoundingInfo();
  83251. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83252. //bring back the rotation
  83253. this.object.rotationQuaternion = q;
  83254. //calculate the world matrix with the new rotation
  83255. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83256. return size;
  83257. }
  83258. else {
  83259. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83260. }
  83261. };
  83262. PhysicsImpostor.prototype.getObjectCenter = function () {
  83263. if (this.object.getBoundingInfo) {
  83264. var boundingInfo = this.object.getBoundingInfo();
  83265. return boundingInfo.boundingBox.centerWorld;
  83266. }
  83267. else {
  83268. return this.object.position;
  83269. }
  83270. };
  83271. /**
  83272. * Get a specific parametes from the options parameter.
  83273. */
  83274. PhysicsImpostor.prototype.getParam = function (paramName) {
  83275. return this._options[paramName];
  83276. };
  83277. /**
  83278. * Sets a specific parameter in the options given to the physics plugin
  83279. */
  83280. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83281. this._options[paramName] = value;
  83282. this._bodyUpdateRequired = true;
  83283. };
  83284. /**
  83285. * Specifically change the body's mass option. Won't recreate the physics body object
  83286. */
  83287. PhysicsImpostor.prototype.setMass = function (mass) {
  83288. if (this.getParam("mass") !== mass) {
  83289. this.setParam("mass", mass);
  83290. }
  83291. if (this._physicsEngine) {
  83292. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83293. }
  83294. };
  83295. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83296. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83297. };
  83298. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83299. if (this._physicsEngine) {
  83300. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83301. }
  83302. };
  83303. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83304. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83305. };
  83306. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83307. if (this._physicsEngine) {
  83308. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83309. }
  83310. };
  83311. /**
  83312. * Execute a function with the physics plugin native code.
  83313. * Provide a function the will have two variables - the world object and the physics body object.
  83314. */
  83315. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83316. if (this._physicsEngine) {
  83317. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83318. }
  83319. };
  83320. /**
  83321. * Register a function that will be executed before the physics world is stepping forward.
  83322. */
  83323. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83324. this._onBeforePhysicsStepCallbacks.push(func);
  83325. };
  83326. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83327. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83328. if (index > -1) {
  83329. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83330. }
  83331. else {
  83332. BABYLON.Tools.Warn("Function to remove was not found");
  83333. }
  83334. };
  83335. /**
  83336. * Register a function that will be executed after the physics step
  83337. */
  83338. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83339. this._onAfterPhysicsStepCallbacks.push(func);
  83340. };
  83341. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83342. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83343. if (index > -1) {
  83344. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83345. }
  83346. else {
  83347. BABYLON.Tools.Warn("Function to remove was not found");
  83348. }
  83349. };
  83350. /**
  83351. * register a function that will be executed when this impostor collides against a different body.
  83352. */
  83353. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83354. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83355. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83356. };
  83357. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83358. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83359. var index = -1;
  83360. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83361. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83362. // chcek the arrays match
  83363. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83364. return collidedAgainstList.indexOf(impostor) > -1;
  83365. });
  83366. if (sameList) {
  83367. index = idx;
  83368. }
  83369. return sameList;
  83370. }
  83371. return false;
  83372. });
  83373. if (found) {
  83374. this._onPhysicsCollideCallbacks.splice(index, 1);
  83375. }
  83376. else {
  83377. BABYLON.Tools.Warn("Function to remove was not found");
  83378. }
  83379. };
  83380. PhysicsImpostor.prototype.getParentsRotation = function () {
  83381. var parent = this.object.parent;
  83382. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83383. while (parent) {
  83384. if (parent.rotationQuaternion) {
  83385. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83386. }
  83387. else {
  83388. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83389. }
  83390. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83391. parent = parent.parent;
  83392. }
  83393. return this._tmpQuat;
  83394. };
  83395. /**
  83396. * Apply a force
  83397. */
  83398. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83399. if (this._physicsEngine) {
  83400. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83401. }
  83402. return this;
  83403. };
  83404. /**
  83405. * Apply an impulse
  83406. */
  83407. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83408. if (this._physicsEngine) {
  83409. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83410. }
  83411. return this;
  83412. };
  83413. /**
  83414. * A help function to create a joint.
  83415. */
  83416. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83417. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83418. this.addJoint(otherImpostor, joint);
  83419. return this;
  83420. };
  83421. /**
  83422. * Add a joint to this impostor with a different impostor.
  83423. */
  83424. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83425. this._joints.push({
  83426. otherImpostor: otherImpostor,
  83427. joint: joint
  83428. });
  83429. if (this._physicsEngine) {
  83430. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83431. }
  83432. return this;
  83433. };
  83434. /**
  83435. * Will keep this body still, in a sleep mode.
  83436. */
  83437. PhysicsImpostor.prototype.sleep = function () {
  83438. if (this._physicsEngine) {
  83439. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83440. }
  83441. return this;
  83442. };
  83443. /**
  83444. * Wake the body up.
  83445. */
  83446. PhysicsImpostor.prototype.wakeUp = function () {
  83447. if (this._physicsEngine) {
  83448. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83449. }
  83450. return this;
  83451. };
  83452. PhysicsImpostor.prototype.clone = function (newObject) {
  83453. if (!newObject)
  83454. return null;
  83455. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83456. };
  83457. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83458. var _this = this;
  83459. //no dispose if no physics engine is available.
  83460. if (!this._physicsEngine) {
  83461. return;
  83462. }
  83463. this._joints.forEach(function (j) {
  83464. if (_this._physicsEngine) {
  83465. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83466. }
  83467. });
  83468. //dispose the physics body
  83469. this._physicsEngine.removeImpostor(this);
  83470. if (this.parent) {
  83471. this.parent.forceUpdate();
  83472. }
  83473. else {
  83474. /*this._object.getChildMeshes().forEach(function(mesh) {
  83475. if (mesh.physicsImpostor) {
  83476. if (disposeChildren) {
  83477. mesh.physicsImpostor.dispose();
  83478. mesh.physicsImpostor = null;
  83479. }
  83480. }
  83481. })*/
  83482. }
  83483. this._isDisposed = true;
  83484. };
  83485. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83486. this._deltaPosition.copyFrom(position);
  83487. };
  83488. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83489. if (!this._deltaRotation) {
  83490. this._deltaRotation = new BABYLON.Quaternion();
  83491. }
  83492. this._deltaRotation.copyFrom(rotation);
  83493. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83494. };
  83495. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83496. if (this._physicsEngine) {
  83497. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83498. }
  83499. return this;
  83500. };
  83501. PhysicsImpostor.prototype.getRadius = function () {
  83502. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83503. };
  83504. /**
  83505. * Sync a bone with this impostor
  83506. * @param bone The bone to sync to the impostor.
  83507. * @param boneMesh The mesh that the bone is influencing.
  83508. * @param jointPivot The pivot of the joint / bone in local space.
  83509. * @param distToJoint Optional distance from the impostor to the joint.
  83510. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83511. */
  83512. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83513. var tempVec = PhysicsImpostor._tmpVecs[0];
  83514. var mesh = this.object;
  83515. if (mesh.rotationQuaternion) {
  83516. if (adjustRotation) {
  83517. var tempQuat = PhysicsImpostor._tmpQuat;
  83518. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83519. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83520. }
  83521. else {
  83522. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83523. }
  83524. }
  83525. tempVec.x = 0;
  83526. tempVec.y = 0;
  83527. tempVec.z = 0;
  83528. if (jointPivot) {
  83529. tempVec.x = jointPivot.x;
  83530. tempVec.y = jointPivot.y;
  83531. tempVec.z = jointPivot.z;
  83532. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83533. if (distToJoint === undefined || distToJoint === null) {
  83534. distToJoint = jointPivot.length();
  83535. }
  83536. tempVec.x *= distToJoint;
  83537. tempVec.y *= distToJoint;
  83538. tempVec.z *= distToJoint;
  83539. }
  83540. if (bone.getParent()) {
  83541. tempVec.addInPlace(mesh.getAbsolutePosition());
  83542. bone.setAbsolutePosition(tempVec, boneMesh);
  83543. }
  83544. else {
  83545. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83546. boneMesh.position.x -= tempVec.x;
  83547. boneMesh.position.y -= tempVec.y;
  83548. boneMesh.position.z -= tempVec.z;
  83549. }
  83550. };
  83551. /**
  83552. * Sync impostor to a bone
  83553. * @param bone The bone that the impostor will be synced to.
  83554. * @param boneMesh The mesh that the bone is influencing.
  83555. * @param jointPivot The pivot of the joint / bone in local space.
  83556. * @param distToJoint Optional distance from the impostor to the joint.
  83557. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83558. * @param boneAxis Optional vector3 axis the bone is aligned with
  83559. */
  83560. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83561. var mesh = this.object;
  83562. if (mesh.rotationQuaternion) {
  83563. if (adjustRotation) {
  83564. var tempQuat = PhysicsImpostor._tmpQuat;
  83565. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83566. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83567. }
  83568. else {
  83569. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83570. }
  83571. }
  83572. var pos = PhysicsImpostor._tmpVecs[0];
  83573. var boneDir = PhysicsImpostor._tmpVecs[1];
  83574. if (!boneAxis) {
  83575. boneAxis = PhysicsImpostor._tmpVecs[2];
  83576. boneAxis.x = 0;
  83577. boneAxis.y = 1;
  83578. boneAxis.z = 0;
  83579. }
  83580. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83581. bone.getAbsolutePositionToRef(boneMesh, pos);
  83582. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83583. distToJoint = jointPivot.length();
  83584. }
  83585. if (distToJoint !== undefined && distToJoint !== null) {
  83586. pos.x += boneDir.x * distToJoint;
  83587. pos.y += boneDir.y * distToJoint;
  83588. pos.z += boneDir.z * distToJoint;
  83589. }
  83590. mesh.setAbsolutePosition(pos);
  83591. };
  83592. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83593. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83594. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83595. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83596. //Impostor types
  83597. PhysicsImpostor.NoImpostor = 0;
  83598. PhysicsImpostor.SphereImpostor = 1;
  83599. PhysicsImpostor.BoxImpostor = 2;
  83600. PhysicsImpostor.PlaneImpostor = 3;
  83601. PhysicsImpostor.MeshImpostor = 4;
  83602. PhysicsImpostor.CylinderImpostor = 7;
  83603. PhysicsImpostor.ParticleImpostor = 8;
  83604. PhysicsImpostor.HeightmapImpostor = 9;
  83605. return PhysicsImpostor;
  83606. }());
  83607. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83608. })(BABYLON || (BABYLON = {}));
  83609. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83610. var BABYLON;
  83611. (function (BABYLON) {
  83612. var PhysicsEngine = /** @class */ (function () {
  83613. function PhysicsEngine(gravity, _physicsPlugin) {
  83614. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83615. this._physicsPlugin = _physicsPlugin;
  83616. //new methods and parameters
  83617. this._impostors = [];
  83618. this._joints = [];
  83619. if (!this._physicsPlugin.isSupported()) {
  83620. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83621. + "Please make sure it is included.");
  83622. }
  83623. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83624. this.setGravity(gravity);
  83625. this.setTimeStep();
  83626. }
  83627. PhysicsEngine.prototype.setGravity = function (gravity) {
  83628. this.gravity = gravity;
  83629. this._physicsPlugin.setGravity(this.gravity);
  83630. };
  83631. /**
  83632. * Set the time step of the physics engine.
  83633. * default is 1/60.
  83634. * To slow it down, enter 1/600 for example.
  83635. * To speed it up, 1/30
  83636. * @param {number} newTimeStep the new timestep to apply to this world.
  83637. */
  83638. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83639. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83640. this._physicsPlugin.setTimeStep(newTimeStep);
  83641. };
  83642. /**
  83643. * Get the time step of the physics engine.
  83644. */
  83645. PhysicsEngine.prototype.getTimeStep = function () {
  83646. return this._physicsPlugin.getTimeStep();
  83647. };
  83648. PhysicsEngine.prototype.dispose = function () {
  83649. this._impostors.forEach(function (impostor) {
  83650. impostor.dispose();
  83651. });
  83652. this._physicsPlugin.dispose();
  83653. };
  83654. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83655. return this._physicsPlugin.name;
  83656. };
  83657. /**
  83658. * Adding a new impostor for the impostor tracking.
  83659. * This will be done by the impostor itself.
  83660. * @param {PhysicsImpostor} impostor the impostor to add
  83661. */
  83662. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83663. impostor.uniqueId = this._impostors.push(impostor);
  83664. //if no parent, generate the body
  83665. if (!impostor.parent) {
  83666. this._physicsPlugin.generatePhysicsBody(impostor);
  83667. }
  83668. };
  83669. /**
  83670. * Remove an impostor from the engine.
  83671. * This impostor and its mesh will not longer be updated by the physics engine.
  83672. * @param {PhysicsImpostor} impostor the impostor to remove
  83673. */
  83674. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83675. var index = this._impostors.indexOf(impostor);
  83676. if (index > -1) {
  83677. var removed = this._impostors.splice(index, 1);
  83678. //Is it needed?
  83679. if (removed.length) {
  83680. //this will also remove it from the world.
  83681. removed[0].physicsBody = null;
  83682. }
  83683. }
  83684. };
  83685. /**
  83686. * Add a joint to the physics engine
  83687. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83688. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83689. * @param {PhysicsJoint} the joint that will connect both impostors.
  83690. */
  83691. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83692. var impostorJoint = {
  83693. mainImpostor: mainImpostor,
  83694. connectedImpostor: connectedImpostor,
  83695. joint: joint
  83696. };
  83697. joint.physicsPlugin = this._physicsPlugin;
  83698. this._joints.push(impostorJoint);
  83699. this._physicsPlugin.generateJoint(impostorJoint);
  83700. };
  83701. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83702. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83703. return (impostorJoint.connectedImpostor === connectedImpostor
  83704. && impostorJoint.joint === joint
  83705. && impostorJoint.mainImpostor === mainImpostor);
  83706. });
  83707. if (matchingJoints.length) {
  83708. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83709. //TODO remove it from the list as well
  83710. }
  83711. };
  83712. /**
  83713. * Called by the scene. no need to call it.
  83714. */
  83715. PhysicsEngine.prototype._step = function (delta) {
  83716. var _this = this;
  83717. //check if any mesh has no body / requires an update
  83718. this._impostors.forEach(function (impostor) {
  83719. if (impostor.isBodyInitRequired()) {
  83720. _this._physicsPlugin.generatePhysicsBody(impostor);
  83721. }
  83722. });
  83723. if (delta > 0.1) {
  83724. delta = 0.1;
  83725. }
  83726. else if (delta <= 0) {
  83727. delta = 1.0 / 60.0;
  83728. }
  83729. this._physicsPlugin.executeStep(delta, this._impostors);
  83730. };
  83731. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83732. return this._physicsPlugin;
  83733. };
  83734. PhysicsEngine.prototype.getImpostors = function () {
  83735. return this._impostors;
  83736. };
  83737. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83738. for (var i = 0; i < this._impostors.length; ++i) {
  83739. if (this._impostors[i].object === object) {
  83740. return this._impostors[i];
  83741. }
  83742. }
  83743. return null;
  83744. };
  83745. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83746. for (var i = 0; i < this._impostors.length; ++i) {
  83747. if (this._impostors[i].physicsBody === body) {
  83748. return this._impostors[i];
  83749. }
  83750. }
  83751. return null;
  83752. };
  83753. // Statics
  83754. PhysicsEngine.Epsilon = 0.001;
  83755. return PhysicsEngine;
  83756. }());
  83757. BABYLON.PhysicsEngine = PhysicsEngine;
  83758. })(BABYLON || (BABYLON = {}));
  83759. //# sourceMappingURL=babylon.physicsEngine.js.map
  83760. var BABYLON;
  83761. (function (BABYLON) {
  83762. var PhysicsHelper = /** @class */ (function () {
  83763. function PhysicsHelper(scene) {
  83764. this._scene = scene;
  83765. this._physicsEngine = this._scene.getPhysicsEngine();
  83766. if (!this._physicsEngine) {
  83767. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83768. }
  83769. }
  83770. /**
  83771. * @param {Vector3} origin the origin of the explosion
  83772. * @param {number} radius the explosion radius
  83773. * @param {number} strength the explosion strength
  83774. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83775. */
  83776. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83777. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83778. if (!this._physicsEngine) {
  83779. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83780. return null;
  83781. }
  83782. var impostors = this._physicsEngine.getImpostors();
  83783. if (impostors.length === 0) {
  83784. return null;
  83785. }
  83786. var event = new PhysicsRadialExplosionEvent(this._scene);
  83787. impostors.forEach(function (impostor) {
  83788. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83789. if (!impostorForceAndContactPoint) {
  83790. return;
  83791. }
  83792. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83793. });
  83794. event.dispose(false);
  83795. return event;
  83796. };
  83797. /**
  83798. * @param {Vector3} origin the origin of the explosion
  83799. * @param {number} radius the explosion radius
  83800. * @param {number} strength the explosion strength
  83801. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83802. */
  83803. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83804. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83805. if (!this._physicsEngine) {
  83806. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83807. return null;
  83808. }
  83809. var impostors = this._physicsEngine.getImpostors();
  83810. if (impostors.length === 0) {
  83811. return null;
  83812. }
  83813. var event = new PhysicsRadialExplosionEvent(this._scene);
  83814. impostors.forEach(function (impostor) {
  83815. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83816. if (!impostorForceAndContactPoint) {
  83817. return;
  83818. }
  83819. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83820. });
  83821. event.dispose(false);
  83822. return event;
  83823. };
  83824. /**
  83825. * @param {Vector3} origin the origin of the explosion
  83826. * @param {number} radius the explosion radius
  83827. * @param {number} strength the explosion strength
  83828. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83829. */
  83830. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83831. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83832. if (!this._physicsEngine) {
  83833. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83834. return null;
  83835. }
  83836. var impostors = this._physicsEngine.getImpostors();
  83837. if (impostors.length === 0) {
  83838. return null;
  83839. }
  83840. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83841. event.dispose(false);
  83842. return event;
  83843. };
  83844. /**
  83845. * @param {Vector3} origin the origin of the updraft
  83846. * @param {number} radius the radius of the updraft
  83847. * @param {number} strength the strength of the updraft
  83848. * @param {number} height the height of the updraft
  83849. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83850. */
  83851. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83852. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83853. if (!this._physicsEngine) {
  83854. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83855. return null;
  83856. }
  83857. if (this._physicsEngine.getImpostors().length === 0) {
  83858. return null;
  83859. }
  83860. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83861. event.dispose(false);
  83862. return event;
  83863. };
  83864. /**
  83865. * @param {Vector3} origin the of the vortex
  83866. * @param {number} radius the radius of the vortex
  83867. * @param {number} strength the strength of the vortex
  83868. * @param {number} height the height of the vortex
  83869. */
  83870. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83871. if (!this._physicsEngine) {
  83872. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83873. return null;
  83874. }
  83875. if (this._physicsEngine.getImpostors().length === 0) {
  83876. return null;
  83877. }
  83878. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83879. event.dispose(false);
  83880. return event;
  83881. };
  83882. return PhysicsHelper;
  83883. }());
  83884. BABYLON.PhysicsHelper = PhysicsHelper;
  83885. /***** Radial explosion *****/
  83886. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83887. function PhysicsRadialExplosionEvent(scene) {
  83888. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83889. this._rays = [];
  83890. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83891. this._scene = scene;
  83892. }
  83893. /**
  83894. * Returns the data related to the radial explosion event (sphere & rays).
  83895. * @returns {PhysicsRadialExplosionEventData}
  83896. */
  83897. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83898. this._dataFetched = true;
  83899. return {
  83900. sphere: this._sphere,
  83901. rays: this._rays,
  83902. };
  83903. };
  83904. /**
  83905. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83906. * @param impostor
  83907. * @param {Vector3} origin the origin of the explosion
  83908. * @param {number} radius the explosion radius
  83909. * @param {number} strength the explosion strength
  83910. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83911. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83912. */
  83913. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83914. if (impostor.mass === 0) {
  83915. return null;
  83916. }
  83917. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83918. return null;
  83919. }
  83920. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83921. return null;
  83922. }
  83923. var impostorObjectCenter = impostor.getObjectCenter();
  83924. var direction = impostorObjectCenter.subtract(origin);
  83925. var ray = new BABYLON.Ray(origin, direction, radius);
  83926. this._rays.push(ray);
  83927. var hit = ray.intersectsMesh(impostor.object);
  83928. var contactPoint = hit.pickedPoint;
  83929. if (!contactPoint) {
  83930. return null;
  83931. }
  83932. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83933. if (distanceFromOrigin > radius) {
  83934. return null;
  83935. }
  83936. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83937. ? strength
  83938. : strength * (1 - (distanceFromOrigin / radius));
  83939. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83940. return { force: force, contactPoint: contactPoint };
  83941. };
  83942. /**
  83943. * Disposes the sphere.
  83944. * @param {bolean} force
  83945. */
  83946. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83947. var _this = this;
  83948. if (force === void 0) { force = true; }
  83949. if (force) {
  83950. this._sphere.dispose();
  83951. }
  83952. else {
  83953. setTimeout(function () {
  83954. if (!_this._dataFetched) {
  83955. _this._sphere.dispose();
  83956. }
  83957. }, 0);
  83958. }
  83959. };
  83960. /*** Helpers ***/
  83961. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83962. if (!this._sphere) {
  83963. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83964. this._sphere.isVisible = false;
  83965. }
  83966. };
  83967. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83968. var impostorObject = impostor.object;
  83969. this._prepareSphere();
  83970. this._sphere.position = origin;
  83971. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83972. this._sphere._updateBoundingInfo();
  83973. this._sphere.computeWorldMatrix(true);
  83974. return this._sphere.intersectsMesh(impostorObject, true);
  83975. };
  83976. return PhysicsRadialExplosionEvent;
  83977. }());
  83978. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83979. /***** Gravitational Field *****/
  83980. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83981. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83982. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83983. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83984. this._physicsHelper = physicsHelper;
  83985. this._scene = scene;
  83986. this._origin = origin;
  83987. this._radius = radius;
  83988. this._strength = strength;
  83989. this._falloff = falloff;
  83990. this._tickCallback = this._tick.bind(this);
  83991. }
  83992. /**
  83993. * Returns the data related to the gravitational field event (sphere).
  83994. * @returns {PhysicsGravitationalFieldEventData}
  83995. */
  83996. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83997. this._dataFetched = true;
  83998. return {
  83999. sphere: this._sphere,
  84000. };
  84001. };
  84002. /**
  84003. * Enables the gravitational field.
  84004. */
  84005. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84006. this._tickCallback.call(this);
  84007. this._scene.registerBeforeRender(this._tickCallback);
  84008. };
  84009. /**
  84010. * Disables the gravitational field.
  84011. */
  84012. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84013. this._scene.unregisterBeforeRender(this._tickCallback);
  84014. };
  84015. /**
  84016. * Disposes the sphere.
  84017. * @param {bolean} force
  84018. */
  84019. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84020. var _this = this;
  84021. if (force === void 0) { force = true; }
  84022. if (force) {
  84023. this._sphere.dispose();
  84024. }
  84025. else {
  84026. setTimeout(function () {
  84027. if (!_this._dataFetched) {
  84028. _this._sphere.dispose();
  84029. }
  84030. }, 0);
  84031. }
  84032. };
  84033. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84034. // Since the params won't change, we fetch the event only once
  84035. if (this._sphere) {
  84036. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84037. }
  84038. else {
  84039. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84040. if (radialExplosionEvent) {
  84041. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84042. }
  84043. }
  84044. };
  84045. return PhysicsGravitationalFieldEvent;
  84046. }());
  84047. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84048. /***** Updraft *****/
  84049. var PhysicsUpdraftEvent = /** @class */ (function () {
  84050. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84051. this._scene = _scene;
  84052. this._origin = _origin;
  84053. this._radius = _radius;
  84054. this._strength = _strength;
  84055. this._height = _height;
  84056. this._updraftMode = _updraftMode;
  84057. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84058. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84059. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84060. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84061. this._physicsEngine = this._scene.getPhysicsEngine();
  84062. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84063. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84064. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84065. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84066. }
  84067. this._tickCallback = this._tick.bind(this);
  84068. }
  84069. /**
  84070. * Returns the data related to the updraft event (cylinder).
  84071. * @returns {PhysicsUpdraftEventData}
  84072. */
  84073. PhysicsUpdraftEvent.prototype.getData = function () {
  84074. this._dataFetched = true;
  84075. return {
  84076. cylinder: this._cylinder,
  84077. };
  84078. };
  84079. /**
  84080. * Enables the updraft.
  84081. */
  84082. PhysicsUpdraftEvent.prototype.enable = function () {
  84083. this._tickCallback.call(this);
  84084. this._scene.registerBeforeRender(this._tickCallback);
  84085. };
  84086. /**
  84087. * Disables the cortex.
  84088. */
  84089. PhysicsUpdraftEvent.prototype.disable = function () {
  84090. this._scene.unregisterBeforeRender(this._tickCallback);
  84091. };
  84092. /**
  84093. * Disposes the sphere.
  84094. * @param {bolean} force
  84095. */
  84096. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84097. var _this = this;
  84098. if (force === void 0) { force = true; }
  84099. if (force) {
  84100. this._cylinder.dispose();
  84101. }
  84102. else {
  84103. setTimeout(function () {
  84104. if (!_this._dataFetched) {
  84105. _this._cylinder.dispose();
  84106. }
  84107. }, 0);
  84108. }
  84109. };
  84110. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84111. if (impostor.mass === 0) {
  84112. return null;
  84113. }
  84114. if (!this._intersectsWithCylinder(impostor)) {
  84115. return null;
  84116. }
  84117. var impostorObjectCenter = impostor.getObjectCenter();
  84118. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84119. var direction = this._originDirection;
  84120. }
  84121. else {
  84122. var direction = impostorObjectCenter.subtract(this._originTop);
  84123. }
  84124. var multiplier = this._strength * -1;
  84125. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84126. return { force: force, contactPoint: impostorObjectCenter };
  84127. };
  84128. PhysicsUpdraftEvent.prototype._tick = function () {
  84129. var _this = this;
  84130. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84131. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84132. if (!impostorForceAndContactPoint) {
  84133. return;
  84134. }
  84135. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84136. });
  84137. };
  84138. /*** Helpers ***/
  84139. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84140. if (!this._cylinder) {
  84141. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84142. height: this._height,
  84143. diameter: this._radius * 2,
  84144. }, this._scene);
  84145. this._cylinder.isVisible = false;
  84146. }
  84147. };
  84148. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84149. var impostorObject = impostor.object;
  84150. this._prepareCylinder();
  84151. this._cylinder.position = this._cylinderPosition;
  84152. return this._cylinder.intersectsMesh(impostorObject, true);
  84153. };
  84154. return PhysicsUpdraftEvent;
  84155. }());
  84156. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84157. /***** Vortex *****/
  84158. var PhysicsVortexEvent = /** @class */ (function () {
  84159. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84160. this._scene = _scene;
  84161. this._origin = _origin;
  84162. this._radius = _radius;
  84163. this._strength = _strength;
  84164. this._height = _height;
  84165. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84166. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84167. this._updraftMultiplier = 0.02;
  84168. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84169. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84170. this._physicsEngine = this._scene.getPhysicsEngine();
  84171. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84172. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84173. this._tickCallback = this._tick.bind(this);
  84174. }
  84175. /**
  84176. * Returns the data related to the vortex event (cylinder).
  84177. * @returns {PhysicsVortexEventData}
  84178. */
  84179. PhysicsVortexEvent.prototype.getData = function () {
  84180. this._dataFetched = true;
  84181. return {
  84182. cylinder: this._cylinder,
  84183. };
  84184. };
  84185. /**
  84186. * Enables the vortex.
  84187. */
  84188. PhysicsVortexEvent.prototype.enable = function () {
  84189. this._tickCallback.call(this);
  84190. this._scene.registerBeforeRender(this._tickCallback);
  84191. };
  84192. /**
  84193. * Disables the cortex.
  84194. */
  84195. PhysicsVortexEvent.prototype.disable = function () {
  84196. this._scene.unregisterBeforeRender(this._tickCallback);
  84197. };
  84198. /**
  84199. * Disposes the sphere.
  84200. * @param {bolean} force
  84201. */
  84202. PhysicsVortexEvent.prototype.dispose = function (force) {
  84203. var _this = this;
  84204. if (force === void 0) { force = true; }
  84205. if (force) {
  84206. this._cylinder.dispose();
  84207. }
  84208. else {
  84209. setTimeout(function () {
  84210. if (!_this._dataFetched) {
  84211. _this._cylinder.dispose();
  84212. }
  84213. }, 0);
  84214. }
  84215. };
  84216. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84217. if (impostor.mass === 0) {
  84218. return null;
  84219. }
  84220. if (!this._intersectsWithCylinder(impostor)) {
  84221. return null;
  84222. }
  84223. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84224. return null;
  84225. }
  84226. var impostorObjectCenter = impostor.getObjectCenter();
  84227. 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)
  84228. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84229. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84230. var hit = ray.intersectsMesh(impostor.object);
  84231. var contactPoint = hit.pickedPoint;
  84232. if (!contactPoint) {
  84233. return null;
  84234. }
  84235. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84236. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84237. var directionToOrigin = contactPoint.normalize();
  84238. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84239. directionToOrigin = directionToOrigin.negate();
  84240. }
  84241. // TODO: find a more physically based solution
  84242. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84243. var forceX = directionToOrigin.x * this._strength / 8;
  84244. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84245. var forceZ = directionToOrigin.z * this._strength / 8;
  84246. }
  84247. else {
  84248. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84249. var forceY = this._originTop.y * this._updraftMultiplier;
  84250. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84251. }
  84252. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84253. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84254. return { force: force, contactPoint: impostorObjectCenter };
  84255. };
  84256. PhysicsVortexEvent.prototype._tick = function () {
  84257. var _this = this;
  84258. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84259. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84260. if (!impostorForceAndContactPoint) {
  84261. return;
  84262. }
  84263. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84264. });
  84265. };
  84266. /*** Helpers ***/
  84267. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84268. if (!this._cylinder) {
  84269. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84270. height: this._height,
  84271. diameter: this._radius * 2,
  84272. }, this._scene);
  84273. this._cylinder.isVisible = false;
  84274. }
  84275. };
  84276. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84277. var impostorObject = impostor.object;
  84278. this._prepareCylinder();
  84279. this._cylinder.position = this._cylinderPosition;
  84280. return this._cylinder.intersectsMesh(impostorObject, true);
  84281. };
  84282. return PhysicsVortexEvent;
  84283. }());
  84284. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84285. /***** Enums *****/
  84286. /**
  84287. * The strenght of the force in correspondence to the distance of the affected object
  84288. */
  84289. var PhysicsRadialImpulseFalloff;
  84290. (function (PhysicsRadialImpulseFalloff) {
  84291. /** Defines that impulse is constant in strength across it's whole radius */
  84292. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84293. /** DEfines that impulse gets weaker if it's further from the origin */
  84294. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84295. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84296. /**
  84297. * The strenght of the force in correspondence to the distance of the affected object
  84298. */
  84299. var PhysicsUpdraftMode;
  84300. (function (PhysicsUpdraftMode) {
  84301. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84302. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84303. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84304. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84305. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84306. })(BABYLON || (BABYLON = {}));
  84307. //# sourceMappingURL=babylon.physicsHelper.js.map
  84308. var BABYLON;
  84309. (function (BABYLON) {
  84310. var CannonJSPlugin = /** @class */ (function () {
  84311. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84312. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84313. if (iterations === void 0) { iterations = 10; }
  84314. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84315. this.name = "CannonJSPlugin";
  84316. this._physicsMaterials = new Array();
  84317. this._fixedTimeStep = 1 / 60;
  84318. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84319. this.BJSCANNON = CANNON;
  84320. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84321. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84322. this._tmpPosition = BABYLON.Vector3.Zero();
  84323. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84324. this._tmpUnityRotation = new BABYLON.Quaternion();
  84325. if (!this.isSupported()) {
  84326. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84327. return;
  84328. }
  84329. this._extendNamespace();
  84330. this.world = new this.BJSCANNON.World();
  84331. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84332. this.world.solver.iterations = iterations;
  84333. }
  84334. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84335. this.world.gravity.copy(gravity);
  84336. };
  84337. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84338. this._fixedTimeStep = timeStep;
  84339. };
  84340. CannonJSPlugin.prototype.getTimeStep = function () {
  84341. return this._fixedTimeStep;
  84342. };
  84343. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84344. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84345. };
  84346. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84347. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84348. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84349. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84350. };
  84351. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84352. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84353. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84354. impostor.physicsBody.applyForce(impulse, worldPoint);
  84355. };
  84356. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84357. //parent-child relationship. Does this impostor has a parent impostor?
  84358. if (impostor.parent) {
  84359. if (impostor.physicsBody) {
  84360. this.removePhysicsBody(impostor);
  84361. //TODO is that needed?
  84362. impostor.forceUpdate();
  84363. }
  84364. return;
  84365. }
  84366. //should a new body be created for this impostor?
  84367. if (impostor.isBodyInitRequired()) {
  84368. var shape = this._createShape(impostor);
  84369. //unregister events, if body is being changed
  84370. var oldBody = impostor.physicsBody;
  84371. if (oldBody) {
  84372. this.removePhysicsBody(impostor);
  84373. }
  84374. //create the body and material
  84375. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84376. var bodyCreationObject = {
  84377. mass: impostor.getParam("mass"),
  84378. material: material
  84379. };
  84380. // A simple extend, in case native options were used.
  84381. var nativeOptions = impostor.getParam("nativeOptions");
  84382. for (var key in nativeOptions) {
  84383. if (nativeOptions.hasOwnProperty(key)) {
  84384. bodyCreationObject[key] = nativeOptions[key];
  84385. }
  84386. }
  84387. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84388. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84389. this.world.addEventListener("preStep", impostor.beforeStep);
  84390. this.world.addEventListener("postStep", impostor.afterStep);
  84391. impostor.physicsBody.addShape(shape);
  84392. this.world.add(impostor.physicsBody);
  84393. //try to keep the body moving in the right direction by taking old properties.
  84394. //Should be tested!
  84395. if (oldBody) {
  84396. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84397. impostor.physicsBody[param].copy(oldBody[param]);
  84398. });
  84399. }
  84400. this._processChildMeshes(impostor);
  84401. }
  84402. //now update the body's transformation
  84403. this._updatePhysicsBodyTransformation(impostor);
  84404. };
  84405. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84406. var _this = this;
  84407. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84408. var currentRotation = mainImpostor.object.rotationQuaternion;
  84409. if (meshChildren.length) {
  84410. var processMesh = function (localPosition, mesh) {
  84411. if (!currentRotation || !mesh.rotationQuaternion) {
  84412. return;
  84413. }
  84414. var childImpostor = mesh.getPhysicsImpostor();
  84415. if (childImpostor) {
  84416. var parent = childImpostor.parent;
  84417. if (parent !== mainImpostor) {
  84418. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84419. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84420. if (childImpostor.physicsBody) {
  84421. _this.removePhysicsBody(childImpostor);
  84422. childImpostor.physicsBody = null;
  84423. }
  84424. childImpostor.parent = mainImpostor;
  84425. childImpostor.resetUpdateFlags();
  84426. 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));
  84427. //Add the mass of the children.
  84428. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84429. }
  84430. }
  84431. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84432. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84433. };
  84434. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84435. }
  84436. };
  84437. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84438. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84439. this.world.removeEventListener("preStep", impostor.beforeStep);
  84440. this.world.removeEventListener("postStep", impostor.afterStep);
  84441. this.world.remove(impostor.physicsBody);
  84442. };
  84443. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84444. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84445. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84446. if (!mainBody || !connectedBody) {
  84447. return;
  84448. }
  84449. var constraint;
  84450. var jointData = impostorJoint.joint.jointData;
  84451. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84452. var constraintData = {
  84453. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84454. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84455. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84456. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84457. maxForce: jointData.nativeParams.maxForce,
  84458. collideConnected: !!jointData.collision
  84459. };
  84460. switch (impostorJoint.joint.type) {
  84461. case BABYLON.PhysicsJoint.HingeJoint:
  84462. case BABYLON.PhysicsJoint.Hinge2Joint:
  84463. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84464. break;
  84465. case BABYLON.PhysicsJoint.DistanceJoint:
  84466. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84467. break;
  84468. case BABYLON.PhysicsJoint.SpringJoint:
  84469. var springData = jointData;
  84470. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84471. restLength: springData.length,
  84472. stiffness: springData.stiffness,
  84473. damping: springData.damping,
  84474. localAnchorA: constraintData.pivotA,
  84475. localAnchorB: constraintData.pivotB
  84476. });
  84477. break;
  84478. case BABYLON.PhysicsJoint.LockJoint:
  84479. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84480. break;
  84481. case BABYLON.PhysicsJoint.PointToPointJoint:
  84482. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84483. default:
  84484. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84485. break;
  84486. }
  84487. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84488. constraint.collideConnected = !!jointData.collision;
  84489. impostorJoint.joint.physicsJoint = constraint;
  84490. //don't add spring as constraint, as it is not one.
  84491. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84492. this.world.addConstraint(constraint);
  84493. }
  84494. else {
  84495. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84496. constraint.applyForce();
  84497. });
  84498. }
  84499. };
  84500. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84501. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84502. };
  84503. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84504. var index;
  84505. var mat;
  84506. for (index = 0; index < this._physicsMaterials.length; index++) {
  84507. mat = this._physicsMaterials[index];
  84508. if (mat.friction === friction && mat.restitution === restitution) {
  84509. return mat;
  84510. }
  84511. }
  84512. var currentMat = new this.BJSCANNON.Material(name);
  84513. currentMat.friction = friction;
  84514. currentMat.restitution = restitution;
  84515. this._physicsMaterials.push(currentMat);
  84516. return currentMat;
  84517. };
  84518. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84519. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84520. };
  84521. CannonJSPlugin.prototype._createShape = function (impostor) {
  84522. var object = impostor.object;
  84523. var returnValue;
  84524. var extendSize = impostor.getObjectExtendSize();
  84525. switch (impostor.type) {
  84526. case BABYLON.PhysicsImpostor.SphereImpostor:
  84527. var radiusX = extendSize.x;
  84528. var radiusY = extendSize.y;
  84529. var radiusZ = extendSize.z;
  84530. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84531. break;
  84532. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84533. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84534. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84535. break;
  84536. case BABYLON.PhysicsImpostor.BoxImpostor:
  84537. var box = extendSize.scale(0.5);
  84538. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84539. break;
  84540. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84541. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84542. returnValue = new this.BJSCANNON.Plane();
  84543. break;
  84544. case BABYLON.PhysicsImpostor.MeshImpostor:
  84545. // should transform the vertex data to world coordinates!!
  84546. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84547. var rawFaces = object.getIndices ? object.getIndices() : [];
  84548. if (!rawVerts)
  84549. return;
  84550. // get only scale! so the object could transform correctly.
  84551. var oldPosition = object.position.clone();
  84552. var oldRotation = object.rotation && object.rotation.clone();
  84553. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84554. object.position.copyFromFloats(0, 0, 0);
  84555. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84556. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84557. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84558. var transform = object.computeWorldMatrix(true);
  84559. // convert rawVerts to object space
  84560. var temp = new Array();
  84561. var index;
  84562. for (index = 0; index < rawVerts.length; index += 3) {
  84563. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84564. }
  84565. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84566. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84567. //now set back the transformation!
  84568. object.position.copyFrom(oldPosition);
  84569. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84570. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84571. break;
  84572. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84573. var oldPosition2 = object.position.clone();
  84574. var oldRotation2 = object.rotation && object.rotation.clone();
  84575. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84576. object.position.copyFromFloats(0, 0, 0);
  84577. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84578. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84579. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84580. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84581. returnValue = this._createHeightmap(object);
  84582. object.position.copyFrom(oldPosition2);
  84583. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84584. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84585. object.computeWorldMatrix(true);
  84586. break;
  84587. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84588. returnValue = new this.BJSCANNON.Particle();
  84589. break;
  84590. }
  84591. return returnValue;
  84592. };
  84593. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84594. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84595. var transform = object.computeWorldMatrix(true);
  84596. // convert rawVerts to object space
  84597. var temp = new Array();
  84598. var index;
  84599. for (index = 0; index < pos.length; index += 3) {
  84600. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84601. }
  84602. pos = temp;
  84603. var matrix = new Array();
  84604. //For now pointDepth will not be used and will be automatically calculated.
  84605. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84606. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84607. var boundingInfo = object.getBoundingInfo();
  84608. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84609. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84610. var elementSize = dim * 2 / arraySize;
  84611. for (var i = 0; i < pos.length; i = i + 3) {
  84612. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84613. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84614. var y = -pos[i + 2] + minY;
  84615. if (!matrix[x]) {
  84616. matrix[x] = [];
  84617. }
  84618. if (!matrix[x][z]) {
  84619. matrix[x][z] = y;
  84620. }
  84621. matrix[x][z] = Math.max(y, matrix[x][z]);
  84622. }
  84623. for (var x = 0; x <= arraySize; ++x) {
  84624. if (!matrix[x]) {
  84625. var loc = 1;
  84626. while (!matrix[(x + loc) % arraySize]) {
  84627. loc++;
  84628. }
  84629. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84630. //console.log("missing x", x);
  84631. }
  84632. for (var z = 0; z <= arraySize; ++z) {
  84633. if (!matrix[x][z]) {
  84634. var loc = 1;
  84635. var newValue;
  84636. while (newValue === undefined) {
  84637. newValue = matrix[x][(z + loc++) % arraySize];
  84638. }
  84639. matrix[x][z] = newValue;
  84640. }
  84641. }
  84642. }
  84643. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84644. elementSize: elementSize
  84645. });
  84646. //For future reference, needed for body transformation
  84647. shape.minY = minY;
  84648. return shape;
  84649. };
  84650. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84651. var object = impostor.object;
  84652. //make sure it is updated...
  84653. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84654. // The delta between the mesh position and the mesh bounding box center
  84655. var bInfo = object.getBoundingInfo();
  84656. if (!bInfo)
  84657. return;
  84658. var center = impostor.getObjectCenter();
  84659. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84660. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84661. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84662. this._tmpPosition.copyFrom(center);
  84663. var quaternion = object.rotationQuaternion;
  84664. if (!quaternion) {
  84665. return;
  84666. }
  84667. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84668. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84669. //-90 DEG in X, precalculated
  84670. quaternion = quaternion.multiply(this._minus90X);
  84671. //Invert! (Precalculated, 90 deg in X)
  84672. //No need to clone. this will never change.
  84673. impostor.setDeltaRotation(this._plus90X);
  84674. }
  84675. //If it is a heightfield, if should be centered.
  84676. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84677. var mesh = object;
  84678. var boundingInfo = mesh.getBoundingInfo();
  84679. //calculate the correct body position:
  84680. var rotationQuaternion = mesh.rotationQuaternion;
  84681. mesh.rotationQuaternion = this._tmpUnityRotation;
  84682. mesh.computeWorldMatrix(true);
  84683. //get original center with no rotation
  84684. var c = center.clone();
  84685. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84686. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84687. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84688. mesh.setPreTransformMatrix(p);
  84689. mesh.computeWorldMatrix(true);
  84690. //calculate the translation
  84691. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84692. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84693. //add it inverted to the delta
  84694. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84695. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84696. //rotation is back
  84697. mesh.rotationQuaternion = rotationQuaternion;
  84698. mesh.setPreTransformMatrix(oldPivot);
  84699. mesh.computeWorldMatrix(true);
  84700. }
  84701. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84702. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84703. //this._tmpPosition.copyFrom(object.position);
  84704. }
  84705. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84706. //Now update the impostor object
  84707. impostor.physicsBody.position.copy(this._tmpPosition);
  84708. impostor.physicsBody.quaternion.copy(quaternion);
  84709. };
  84710. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84711. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84712. if (impostor.object.rotationQuaternion) {
  84713. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84714. }
  84715. };
  84716. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84717. impostor.physicsBody.position.copy(newPosition);
  84718. impostor.physicsBody.quaternion.copy(newRotation);
  84719. };
  84720. CannonJSPlugin.prototype.isSupported = function () {
  84721. return this.BJSCANNON !== undefined;
  84722. };
  84723. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84724. impostor.physicsBody.velocity.copy(velocity);
  84725. };
  84726. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84727. impostor.physicsBody.angularVelocity.copy(velocity);
  84728. };
  84729. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84730. var v = impostor.physicsBody.velocity;
  84731. if (!v) {
  84732. return null;
  84733. }
  84734. return new BABYLON.Vector3(v.x, v.y, v.z);
  84735. };
  84736. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84737. var v = impostor.physicsBody.angularVelocity;
  84738. if (!v) {
  84739. return null;
  84740. }
  84741. return new BABYLON.Vector3(v.x, v.y, v.z);
  84742. };
  84743. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84744. impostor.physicsBody.mass = mass;
  84745. impostor.physicsBody.updateMassProperties();
  84746. };
  84747. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84748. return impostor.physicsBody.mass;
  84749. };
  84750. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84751. return impostor.physicsBody.material.friction;
  84752. };
  84753. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84754. impostor.physicsBody.material.friction = friction;
  84755. };
  84756. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84757. return impostor.physicsBody.material.restitution;
  84758. };
  84759. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84760. impostor.physicsBody.material.restitution = restitution;
  84761. };
  84762. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84763. impostor.physicsBody.sleep();
  84764. };
  84765. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84766. impostor.physicsBody.wakeUp();
  84767. };
  84768. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84769. joint.physicsJoint.distance = maxDistance;
  84770. };
  84771. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84772. // if (!motorIndex) {
  84773. // joint.physicsJoint.enableMotor();
  84774. // }
  84775. // }
  84776. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84777. // if (!motorIndex) {
  84778. // joint.physicsJoint.disableMotor();
  84779. // }
  84780. // }
  84781. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84782. if (!motorIndex) {
  84783. joint.physicsJoint.enableMotor();
  84784. joint.physicsJoint.setMotorSpeed(speed);
  84785. if (maxForce) {
  84786. this.setLimit(joint, maxForce);
  84787. }
  84788. }
  84789. };
  84790. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84791. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84792. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84793. };
  84794. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84795. var body = impostor.physicsBody;
  84796. mesh.position.x = body.position.x;
  84797. mesh.position.y = body.position.y;
  84798. mesh.position.z = body.position.z;
  84799. if (mesh.rotationQuaternion) {
  84800. mesh.rotationQuaternion.x = body.quaternion.x;
  84801. mesh.rotationQuaternion.y = body.quaternion.y;
  84802. mesh.rotationQuaternion.z = body.quaternion.z;
  84803. mesh.rotationQuaternion.w = body.quaternion.w;
  84804. }
  84805. };
  84806. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84807. var shape = impostor.physicsBody.shapes[0];
  84808. return shape.boundingSphereRadius;
  84809. };
  84810. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84811. var shape = impostor.physicsBody.shapes[0];
  84812. result.x = shape.halfExtents.x * 2;
  84813. result.y = shape.halfExtents.y * 2;
  84814. result.z = shape.halfExtents.z * 2;
  84815. };
  84816. CannonJSPlugin.prototype.dispose = function () {
  84817. };
  84818. CannonJSPlugin.prototype._extendNamespace = function () {
  84819. //this will force cannon to execute at least one step when using interpolation
  84820. var step_tmp1 = new this.BJSCANNON.Vec3();
  84821. var Engine = this.BJSCANNON;
  84822. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84823. maxSubSteps = maxSubSteps || 10;
  84824. timeSinceLastCalled = timeSinceLastCalled || 0;
  84825. if (timeSinceLastCalled === 0) {
  84826. this.internalStep(dt);
  84827. this.time += dt;
  84828. }
  84829. else {
  84830. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84831. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84832. var t0 = performance.now();
  84833. for (var i = 0; i !== internalSteps; i++) {
  84834. this.internalStep(dt);
  84835. if (performance.now() - t0 > dt * 1000) {
  84836. break;
  84837. }
  84838. }
  84839. this.time += timeSinceLastCalled;
  84840. var h = this.time % dt;
  84841. var h_div_dt = h / dt;
  84842. var interpvelo = step_tmp1;
  84843. var bodies = this.bodies;
  84844. for (var j = 0; j !== bodies.length; j++) {
  84845. var b = bodies[j];
  84846. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84847. b.position.vsub(b.previousPosition, interpvelo);
  84848. interpvelo.scale(h_div_dt, interpvelo);
  84849. b.position.vadd(interpvelo, b.interpolatedPosition);
  84850. }
  84851. else {
  84852. b.interpolatedPosition.copy(b.position);
  84853. b.interpolatedQuaternion.copy(b.quaternion);
  84854. }
  84855. }
  84856. }
  84857. };
  84858. };
  84859. return CannonJSPlugin;
  84860. }());
  84861. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84862. })(BABYLON || (BABYLON = {}));
  84863. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84864. var BABYLON;
  84865. (function (BABYLON) {
  84866. var OimoJSPlugin = /** @class */ (function () {
  84867. function OimoJSPlugin(iterations) {
  84868. this.name = "OimoJSPlugin";
  84869. this._tmpImpostorsArray = [];
  84870. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84871. this.BJSOIMO = OIMO;
  84872. this.world = new this.BJSOIMO.World({
  84873. iterations: iterations
  84874. });
  84875. this.world.clear();
  84876. }
  84877. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84878. this.world.gravity.copy(gravity);
  84879. };
  84880. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84881. this.world.timeStep = timeStep;
  84882. };
  84883. OimoJSPlugin.prototype.getTimeStep = function () {
  84884. return this.world.timeStep;
  84885. };
  84886. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84887. var _this = this;
  84888. impostors.forEach(function (impostor) {
  84889. impostor.beforeStep();
  84890. });
  84891. this.world.step();
  84892. impostors.forEach(function (impostor) {
  84893. impostor.afterStep();
  84894. //update the ordered impostors array
  84895. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84896. });
  84897. //check for collisions
  84898. var contact = this.world.contacts;
  84899. while (contact !== null) {
  84900. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84901. contact = contact.next;
  84902. continue;
  84903. }
  84904. //is this body colliding with any other? get the impostor
  84905. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84906. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84907. if (!mainImpostor || !collidingImpostor) {
  84908. contact = contact.next;
  84909. continue;
  84910. }
  84911. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84912. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84913. contact = contact.next;
  84914. }
  84915. };
  84916. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84917. var mass = impostor.physicsBody.mass;
  84918. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84919. };
  84920. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84921. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84922. this.applyImpulse(impostor, force, contactPoint);
  84923. };
  84924. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84925. var _this = this;
  84926. //parent-child relationship. Does this impostor has a parent impostor?
  84927. if (impostor.parent) {
  84928. if (impostor.physicsBody) {
  84929. this.removePhysicsBody(impostor);
  84930. //TODO is that needed?
  84931. impostor.forceUpdate();
  84932. }
  84933. return;
  84934. }
  84935. if (impostor.isBodyInitRequired()) {
  84936. var bodyConfig = {
  84937. name: impostor.uniqueId,
  84938. //Oimo must have mass, also for static objects.
  84939. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84940. size: [],
  84941. type: [],
  84942. pos: [],
  84943. posShape: [],
  84944. rot: [],
  84945. rotShape: [],
  84946. move: impostor.getParam("mass") !== 0,
  84947. density: impostor.getParam("mass"),
  84948. friction: impostor.getParam("friction"),
  84949. restitution: impostor.getParam("restitution"),
  84950. //Supporting older versions of Oimo
  84951. world: this.world
  84952. };
  84953. var impostors = [impostor];
  84954. var addToArray = function (parent) {
  84955. if (!parent.getChildMeshes)
  84956. return;
  84957. parent.getChildMeshes().forEach(function (m) {
  84958. if (m.physicsImpostor) {
  84959. impostors.push(m.physicsImpostor);
  84960. //m.physicsImpostor._init();
  84961. }
  84962. });
  84963. };
  84964. addToArray(impostor.object);
  84965. var checkWithEpsilon_1 = function (value) {
  84966. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84967. };
  84968. impostors.forEach(function (i) {
  84969. if (!i.object.rotationQuaternion) {
  84970. return;
  84971. }
  84972. //get the correct bounding box
  84973. var oldQuaternion = i.object.rotationQuaternion;
  84974. var rot = oldQuaternion.toEulerAngles();
  84975. var extendSize = i.getObjectExtendSize();
  84976. var radToDeg = 57.295779513082320876;
  84977. if (i === impostor) {
  84978. var center = impostor.getObjectCenter();
  84979. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84980. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84981. //Can also use Array.prototype.push.apply
  84982. bodyConfig.pos.push(center.x);
  84983. bodyConfig.pos.push(center.y);
  84984. bodyConfig.pos.push(center.z);
  84985. bodyConfig.posShape.push(0, 0, 0);
  84986. //tmp solution
  84987. bodyConfig.rot.push(rot.x * radToDeg);
  84988. bodyConfig.rot.push(rot.y * radToDeg);
  84989. bodyConfig.rot.push(rot.z * radToDeg);
  84990. bodyConfig.rotShape.push(0, 0, 0);
  84991. }
  84992. else {
  84993. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84994. bodyConfig.posShape.push(localPosition.x);
  84995. bodyConfig.posShape.push(localPosition.y);
  84996. bodyConfig.posShape.push(localPosition.z);
  84997. bodyConfig.pos.push(0, 0, 0);
  84998. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84999. bodyConfig.rot.push(0);
  85000. bodyConfig.rot.push(0);
  85001. bodyConfig.rot.push(0);
  85002. bodyConfig.rotShape.push(rot.x * radToDeg);
  85003. bodyConfig.rotShape.push(rot.y * radToDeg);
  85004. bodyConfig.rotShape.push(rot.z * radToDeg);
  85005. }
  85006. // register mesh
  85007. switch (i.type) {
  85008. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85009. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85010. case BABYLON.PhysicsImpostor.SphereImpostor:
  85011. var radiusX = extendSize.x;
  85012. var radiusY = extendSize.y;
  85013. var radiusZ = extendSize.z;
  85014. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85015. bodyConfig.type.push('sphere');
  85016. //due to the way oimo works with compounds, add 3 times
  85017. bodyConfig.size.push(size);
  85018. bodyConfig.size.push(size);
  85019. bodyConfig.size.push(size);
  85020. break;
  85021. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85022. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85023. var sizeY = checkWithEpsilon_1(extendSize.y);
  85024. bodyConfig.type.push('cylinder');
  85025. bodyConfig.size.push(sizeX);
  85026. bodyConfig.size.push(sizeY);
  85027. //due to the way oimo works with compounds, add one more value.
  85028. bodyConfig.size.push(sizeY);
  85029. break;
  85030. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85031. case BABYLON.PhysicsImpostor.BoxImpostor:
  85032. default:
  85033. var sizeX = checkWithEpsilon_1(extendSize.x);
  85034. var sizeY = checkWithEpsilon_1(extendSize.y);
  85035. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85036. bodyConfig.type.push('box');
  85037. //if (i === impostor) {
  85038. bodyConfig.size.push(sizeX);
  85039. bodyConfig.size.push(sizeY);
  85040. bodyConfig.size.push(sizeZ);
  85041. //} else {
  85042. // bodyConfig.size.push(0,0,0);
  85043. //}
  85044. break;
  85045. }
  85046. //actually not needed, but hey...
  85047. i.object.rotationQuaternion = oldQuaternion;
  85048. });
  85049. impostor.physicsBody = this.world.add(bodyConfig);
  85050. }
  85051. else {
  85052. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85053. }
  85054. impostor.setDeltaPosition(this._tmpPositionVector);
  85055. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85056. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85057. };
  85058. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85059. //impostor.physicsBody.dispose();
  85060. //Same as : (older oimo versions)
  85061. this.world.removeRigidBody(impostor.physicsBody);
  85062. };
  85063. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85064. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85065. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85066. if (!mainBody || !connectedBody) {
  85067. return;
  85068. }
  85069. var jointData = impostorJoint.joint.jointData;
  85070. var options = jointData.nativeParams || {};
  85071. var type;
  85072. var nativeJointData = {
  85073. body1: mainBody,
  85074. body2: connectedBody,
  85075. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85076. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85077. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85078. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85079. min: options.min,
  85080. max: options.max,
  85081. collision: options.collision || jointData.collision,
  85082. spring: options.spring,
  85083. //supporting older version of Oimo
  85084. world: this.world
  85085. };
  85086. switch (impostorJoint.joint.type) {
  85087. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85088. type = "jointBall";
  85089. break;
  85090. case BABYLON.PhysicsJoint.SpringJoint:
  85091. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85092. var springData = jointData;
  85093. nativeJointData.min = springData.length || nativeJointData.min;
  85094. //Max should also be set, just make sure it is at least min
  85095. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85096. case BABYLON.PhysicsJoint.DistanceJoint:
  85097. type = "jointDistance";
  85098. nativeJointData.max = jointData.maxDistance;
  85099. break;
  85100. case BABYLON.PhysicsJoint.PrismaticJoint:
  85101. type = "jointPrisme";
  85102. break;
  85103. case BABYLON.PhysicsJoint.SliderJoint:
  85104. type = "jointSlide";
  85105. break;
  85106. case BABYLON.PhysicsJoint.WheelJoint:
  85107. type = "jointWheel";
  85108. break;
  85109. case BABYLON.PhysicsJoint.HingeJoint:
  85110. default:
  85111. type = "jointHinge";
  85112. break;
  85113. }
  85114. nativeJointData.type = type;
  85115. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85116. };
  85117. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85118. //Bug in Oimo prevents us from disposing a joint in the playground
  85119. //joint.joint.physicsJoint.dispose();
  85120. //So we will bruteforce it!
  85121. try {
  85122. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85123. }
  85124. catch (e) {
  85125. BABYLON.Tools.Warn(e);
  85126. }
  85127. };
  85128. OimoJSPlugin.prototype.isSupported = function () {
  85129. return this.BJSOIMO !== undefined;
  85130. };
  85131. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85132. if (!impostor.physicsBody.sleeping) {
  85133. //TODO check that
  85134. /*if (impostor.physicsBody.shapes.next) {
  85135. var parentShape = this._getLastShape(impostor.physicsBody);
  85136. impostor.object.position.copyFrom(parentShape.position);
  85137. console.log(parentShape.position);
  85138. } else {*/
  85139. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85140. //}
  85141. if (impostor.object.rotationQuaternion) {
  85142. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85143. }
  85144. }
  85145. };
  85146. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85147. var body = impostor.physicsBody;
  85148. body.position.copy(newPosition);
  85149. body.orientation.copy(newRotation);
  85150. body.syncShapes();
  85151. body.awake();
  85152. };
  85153. /*private _getLastShape(body: any): any {
  85154. var lastShape = body.shapes;
  85155. while (lastShape.next) {
  85156. lastShape = lastShape.next;
  85157. }
  85158. return lastShape;
  85159. }*/
  85160. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85161. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  85162. };
  85163. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85164. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  85165. };
  85166. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85167. var v = impostor.physicsBody.linearVelocity;
  85168. if (!v) {
  85169. return null;
  85170. }
  85171. return new BABYLON.Vector3(v.x, v.y, v.z);
  85172. };
  85173. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85174. var v = impostor.physicsBody.angularVelocity;
  85175. if (!v) {
  85176. return null;
  85177. }
  85178. return new BABYLON.Vector3(v.x, v.y, v.z);
  85179. };
  85180. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85181. var staticBody = mass === 0;
  85182. //this will actually set the body's density and not its mass.
  85183. //But this is how oimo treats the mass variable.
  85184. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85185. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85186. };
  85187. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85188. return impostor.physicsBody.shapes.density;
  85189. };
  85190. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85191. return impostor.physicsBody.shapes.friction;
  85192. };
  85193. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85194. impostor.physicsBody.shapes.friction = friction;
  85195. };
  85196. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85197. return impostor.physicsBody.shapes.restitution;
  85198. };
  85199. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85200. impostor.physicsBody.shapes.restitution = restitution;
  85201. };
  85202. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85203. impostor.physicsBody.sleep();
  85204. };
  85205. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85206. impostor.physicsBody.awake();
  85207. };
  85208. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85209. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85210. if (minDistance !== void 0) {
  85211. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85212. }
  85213. };
  85214. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85215. //TODO separate rotational and transational motors.
  85216. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85217. if (motor) {
  85218. motor.setMotor(speed, maxForce);
  85219. }
  85220. };
  85221. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85222. //TODO separate rotational and transational motors.
  85223. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85224. if (motor) {
  85225. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85226. }
  85227. };
  85228. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85229. var body = impostor.physicsBody;
  85230. mesh.position.x = body.position.x;
  85231. mesh.position.y = body.position.y;
  85232. mesh.position.z = body.position.z;
  85233. if (mesh.rotationQuaternion) {
  85234. mesh.rotationQuaternion.x = body.orientation.x;
  85235. mesh.rotationQuaternion.y = body.orientation.y;
  85236. mesh.rotationQuaternion.z = body.orientation.z;
  85237. mesh.rotationQuaternion.w = body.orientation.s;
  85238. }
  85239. };
  85240. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85241. return impostor.physicsBody.shapes.radius;
  85242. };
  85243. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85244. var shape = impostor.physicsBody.shapes;
  85245. result.x = shape.halfWidth * 2;
  85246. result.y = shape.halfHeight * 2;
  85247. result.z = shape.halfDepth * 2;
  85248. };
  85249. OimoJSPlugin.prototype.dispose = function () {
  85250. this.world.clear();
  85251. };
  85252. return OimoJSPlugin;
  85253. }());
  85254. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85255. })(BABYLON || (BABYLON = {}));
  85256. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85257. var BABYLON;
  85258. (function (BABYLON) {
  85259. /*
  85260. * Based on jsTGALoader - Javascript loader for TGA file
  85261. * By Vincent Thibault
  85262. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85263. */
  85264. var TGATools = /** @class */ (function () {
  85265. function TGATools() {
  85266. }
  85267. TGATools.GetTGAHeader = function (data) {
  85268. var offset = 0;
  85269. var header = {
  85270. id_length: data[offset++],
  85271. colormap_type: data[offset++],
  85272. image_type: data[offset++],
  85273. colormap_index: data[offset++] | data[offset++] << 8,
  85274. colormap_length: data[offset++] | data[offset++] << 8,
  85275. colormap_size: data[offset++],
  85276. origin: [
  85277. data[offset++] | data[offset++] << 8,
  85278. data[offset++] | data[offset++] << 8
  85279. ],
  85280. width: data[offset++] | data[offset++] << 8,
  85281. height: data[offset++] | data[offset++] << 8,
  85282. pixel_size: data[offset++],
  85283. flags: data[offset++]
  85284. };
  85285. return header;
  85286. };
  85287. TGATools.UploadContent = function (gl, data) {
  85288. // Not enough data to contain header ?
  85289. if (data.length < 19) {
  85290. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85291. return;
  85292. }
  85293. // Read Header
  85294. var offset = 18;
  85295. var header = TGATools.GetTGAHeader(data);
  85296. // Assume it's a valid Targa file.
  85297. if (header.id_length + offset > data.length) {
  85298. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85299. return;
  85300. }
  85301. // Skip not needed data
  85302. offset += header.id_length;
  85303. var use_rle = false;
  85304. var use_pal = false;
  85305. var use_grey = false;
  85306. // Get some informations.
  85307. switch (header.image_type) {
  85308. case TGATools._TYPE_RLE_INDEXED:
  85309. use_rle = true;
  85310. case TGATools._TYPE_INDEXED:
  85311. use_pal = true;
  85312. break;
  85313. case TGATools._TYPE_RLE_RGB:
  85314. use_rle = true;
  85315. case TGATools._TYPE_RGB:
  85316. // use_rgb = true;
  85317. break;
  85318. case TGATools._TYPE_RLE_GREY:
  85319. use_rle = true;
  85320. case TGATools._TYPE_GREY:
  85321. use_grey = true;
  85322. break;
  85323. }
  85324. var pixel_data;
  85325. // var numAlphaBits = header.flags & 0xf;
  85326. var pixel_size = header.pixel_size >> 3;
  85327. var pixel_total = header.width * header.height * pixel_size;
  85328. // Read palettes
  85329. var palettes;
  85330. if (use_pal) {
  85331. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85332. }
  85333. // Read LRE
  85334. if (use_rle) {
  85335. pixel_data = new Uint8Array(pixel_total);
  85336. var c, count, i;
  85337. var localOffset = 0;
  85338. var pixels = new Uint8Array(pixel_size);
  85339. while (offset < pixel_total && localOffset < pixel_total) {
  85340. c = data[offset++];
  85341. count = (c & 0x7f) + 1;
  85342. // RLE pixels
  85343. if (c & 0x80) {
  85344. // Bind pixel tmp array
  85345. for (i = 0; i < pixel_size; ++i) {
  85346. pixels[i] = data[offset++];
  85347. }
  85348. // Copy pixel array
  85349. for (i = 0; i < count; ++i) {
  85350. pixel_data.set(pixels, localOffset + i * pixel_size);
  85351. }
  85352. localOffset += pixel_size * count;
  85353. }
  85354. // Raw pixels
  85355. else {
  85356. count *= pixel_size;
  85357. for (i = 0; i < count; ++i) {
  85358. pixel_data[localOffset + i] = data[offset++];
  85359. }
  85360. localOffset += count;
  85361. }
  85362. }
  85363. }
  85364. // RAW Pixels
  85365. else {
  85366. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85367. }
  85368. // Load to texture
  85369. var x_start, y_start, x_step, y_step, y_end, x_end;
  85370. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85371. default:
  85372. case TGATools._ORIGIN_UL:
  85373. x_start = 0;
  85374. x_step = 1;
  85375. x_end = header.width;
  85376. y_start = 0;
  85377. y_step = 1;
  85378. y_end = header.height;
  85379. break;
  85380. case TGATools._ORIGIN_BL:
  85381. x_start = 0;
  85382. x_step = 1;
  85383. x_end = header.width;
  85384. y_start = header.height - 1;
  85385. y_step = -1;
  85386. y_end = -1;
  85387. break;
  85388. case TGATools._ORIGIN_UR:
  85389. x_start = header.width - 1;
  85390. x_step = -1;
  85391. x_end = -1;
  85392. y_start = 0;
  85393. y_step = 1;
  85394. y_end = header.height;
  85395. break;
  85396. case TGATools._ORIGIN_BR:
  85397. x_start = header.width - 1;
  85398. x_step = -1;
  85399. x_end = -1;
  85400. y_start = header.height - 1;
  85401. y_step = -1;
  85402. y_end = -1;
  85403. break;
  85404. }
  85405. // Load the specify method
  85406. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85407. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85408. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85409. };
  85410. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85411. var image = pixel_data, colormap = palettes;
  85412. var width = header.width, height = header.height;
  85413. var color, i = 0, x, y;
  85414. var imageData = new Uint8Array(width * height * 4);
  85415. for (y = y_start; y !== y_end; y += y_step) {
  85416. for (x = x_start; x !== x_end; x += x_step, i++) {
  85417. color = image[i];
  85418. imageData[(x + width * y) * 4 + 3] = 255;
  85419. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85420. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85421. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85422. }
  85423. }
  85424. return imageData;
  85425. };
  85426. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85427. var image = pixel_data;
  85428. var width = header.width, height = header.height;
  85429. var color, i = 0, x, y;
  85430. var imageData = new Uint8Array(width * height * 4);
  85431. for (y = y_start; y !== y_end; y += y_step) {
  85432. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85433. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85434. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85435. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85436. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85437. imageData[(x + width * y) * 4 + 0] = r;
  85438. imageData[(x + width * y) * 4 + 1] = g;
  85439. imageData[(x + width * y) * 4 + 2] = b;
  85440. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85441. }
  85442. }
  85443. return imageData;
  85444. };
  85445. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85446. var image = pixel_data;
  85447. var width = header.width, height = header.height;
  85448. var i = 0, x, y;
  85449. var imageData = new Uint8Array(width * height * 4);
  85450. for (y = y_start; y !== y_end; y += y_step) {
  85451. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85452. imageData[(x + width * y) * 4 + 3] = 255;
  85453. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85454. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85455. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85456. }
  85457. }
  85458. return imageData;
  85459. };
  85460. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85461. var image = pixel_data;
  85462. var width = header.width, height = header.height;
  85463. var i = 0, x, y;
  85464. var imageData = new Uint8Array(width * height * 4);
  85465. for (y = y_start; y !== y_end; y += y_step) {
  85466. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85467. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85468. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85469. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85470. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85471. }
  85472. }
  85473. return imageData;
  85474. };
  85475. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85476. var image = pixel_data;
  85477. var width = header.width, height = header.height;
  85478. var color, i = 0, x, y;
  85479. var imageData = new Uint8Array(width * height * 4);
  85480. for (y = y_start; y !== y_end; y += y_step) {
  85481. for (x = x_start; x !== x_end; x += x_step, i++) {
  85482. color = image[i];
  85483. imageData[(x + width * y) * 4 + 0] = color;
  85484. imageData[(x + width * y) * 4 + 1] = color;
  85485. imageData[(x + width * y) * 4 + 2] = color;
  85486. imageData[(x + width * y) * 4 + 3] = 255;
  85487. }
  85488. }
  85489. return imageData;
  85490. };
  85491. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85492. var image = pixel_data;
  85493. var width = header.width, height = header.height;
  85494. var i = 0, x, y;
  85495. var imageData = new Uint8Array(width * height * 4);
  85496. for (y = y_start; y !== y_end; y += y_step) {
  85497. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85498. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85499. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85500. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85501. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85502. }
  85503. }
  85504. return imageData;
  85505. };
  85506. //private static _TYPE_NO_DATA = 0;
  85507. TGATools._TYPE_INDEXED = 1;
  85508. TGATools._TYPE_RGB = 2;
  85509. TGATools._TYPE_GREY = 3;
  85510. TGATools._TYPE_RLE_INDEXED = 9;
  85511. TGATools._TYPE_RLE_RGB = 10;
  85512. TGATools._TYPE_RLE_GREY = 11;
  85513. TGATools._ORIGIN_MASK = 0x30;
  85514. TGATools._ORIGIN_SHIFT = 0x04;
  85515. TGATools._ORIGIN_BL = 0x00;
  85516. TGATools._ORIGIN_BR = 0x01;
  85517. TGATools._ORIGIN_UL = 0x02;
  85518. TGATools._ORIGIN_UR = 0x03;
  85519. return TGATools;
  85520. }());
  85521. BABYLON.TGATools = TGATools;
  85522. })(BABYLON || (BABYLON = {}));
  85523. //# sourceMappingURL=babylon.tga.js.map
  85524. var BABYLON;
  85525. (function (BABYLON) {
  85526. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85527. // All values and structures referenced from:
  85528. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85529. var DDS_MAGIC = 0x20534444;
  85530. var
  85531. //DDSD_CAPS = 0x1,
  85532. //DDSD_HEIGHT = 0x2,
  85533. //DDSD_WIDTH = 0x4,
  85534. //DDSD_PITCH = 0x8,
  85535. //DDSD_PIXELFORMAT = 0x1000,
  85536. DDSD_MIPMAPCOUNT = 0x20000;
  85537. //DDSD_LINEARSIZE = 0x80000,
  85538. //DDSD_DEPTH = 0x800000;
  85539. // var DDSCAPS_COMPLEX = 0x8,
  85540. // DDSCAPS_MIPMAP = 0x400000,
  85541. // DDSCAPS_TEXTURE = 0x1000;
  85542. var DDSCAPS2_CUBEMAP = 0x200;
  85543. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85544. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85545. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85546. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85547. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85548. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85549. // DDSCAPS2_VOLUME = 0x200000;
  85550. var
  85551. //DDPF_ALPHAPIXELS = 0x1,
  85552. //DDPF_ALPHA = 0x2,
  85553. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85554. //DDPF_YUV = 0x200,
  85555. DDPF_LUMINANCE = 0x20000;
  85556. function FourCCToInt32(value) {
  85557. return value.charCodeAt(0) +
  85558. (value.charCodeAt(1) << 8) +
  85559. (value.charCodeAt(2) << 16) +
  85560. (value.charCodeAt(3) << 24);
  85561. }
  85562. function Int32ToFourCC(value) {
  85563. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85564. }
  85565. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85566. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85567. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85568. var FOURCC_DX10 = FourCCToInt32("DX10");
  85569. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85570. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85571. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85572. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85573. var headerLengthInt = 31; // The header length in 32 bit ints
  85574. // Offsets into the header array
  85575. var off_magic = 0;
  85576. var off_size = 1;
  85577. var off_flags = 2;
  85578. var off_height = 3;
  85579. var off_width = 4;
  85580. var off_mipmapCount = 7;
  85581. var off_pfFlags = 20;
  85582. var off_pfFourCC = 21;
  85583. var off_RGBbpp = 22;
  85584. var off_RMask = 23;
  85585. var off_GMask = 24;
  85586. var off_BMask = 25;
  85587. var off_AMask = 26;
  85588. // var off_caps1 = 27;
  85589. var off_caps2 = 28;
  85590. // var off_caps3 = 29;
  85591. // var off_caps4 = 30;
  85592. var off_dxgiFormat = 32;
  85593. ;
  85594. var DDSTools = /** @class */ (function () {
  85595. function DDSTools() {
  85596. }
  85597. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85598. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85599. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85600. var mipmapCount = 1;
  85601. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85602. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85603. }
  85604. var fourCC = header[off_pfFourCC];
  85605. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85606. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85607. switch (fourCC) {
  85608. case FOURCC_D3DFMT_R16G16B16A16F:
  85609. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85610. break;
  85611. case FOURCC_D3DFMT_R32G32B32A32F:
  85612. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85613. break;
  85614. case FOURCC_DX10:
  85615. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85616. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85617. break;
  85618. }
  85619. }
  85620. return {
  85621. width: header[off_width],
  85622. height: header[off_height],
  85623. mipmapCount: mipmapCount,
  85624. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85625. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85626. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85627. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85628. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85629. dxgiFormat: dxgiFormat,
  85630. textureType: textureType
  85631. };
  85632. };
  85633. DDSTools._ToHalfFloat = function (value) {
  85634. if (!DDSTools._FloatView) {
  85635. DDSTools._FloatView = new Float32Array(1);
  85636. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85637. }
  85638. DDSTools._FloatView[0] = value;
  85639. var x = DDSTools._Int32View[0];
  85640. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85641. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85642. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85643. /* If zero, or denormal, or exponent underflows too much for a denormal
  85644. * half, return signed zero. */
  85645. if (e < 103) {
  85646. return bits;
  85647. }
  85648. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85649. if (e > 142) {
  85650. bits |= 0x7c00;
  85651. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85652. * not Inf, so make sure we set one mantissa bit too. */
  85653. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85654. return bits;
  85655. }
  85656. /* If exponent underflows but not too much, return a denormal */
  85657. if (e < 113) {
  85658. m |= 0x0800;
  85659. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85660. * to 1, which is OK. */
  85661. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85662. return bits;
  85663. }
  85664. bits |= ((e - 112) << 10) | (m >> 1);
  85665. bits += m & 1;
  85666. return bits;
  85667. };
  85668. DDSTools._FromHalfFloat = function (value) {
  85669. var s = (value & 0x8000) >> 15;
  85670. var e = (value & 0x7C00) >> 10;
  85671. var f = value & 0x03FF;
  85672. if (e === 0) {
  85673. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85674. }
  85675. else if (e == 0x1F) {
  85676. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85677. }
  85678. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85679. };
  85680. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85681. var destArray = new Float32Array(dataLength);
  85682. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85683. var index = 0;
  85684. for (var y = 0; y < height; y++) {
  85685. for (var x = 0; x < width; x++) {
  85686. var srcPos = (x + y * width) * 4;
  85687. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85688. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85689. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85690. if (DDSTools.StoreLODInAlphaChannel) {
  85691. destArray[index + 3] = lod;
  85692. }
  85693. else {
  85694. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85695. }
  85696. index += 4;
  85697. }
  85698. }
  85699. return destArray;
  85700. };
  85701. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85702. if (DDSTools.StoreLODInAlphaChannel) {
  85703. var destArray = new Uint16Array(dataLength);
  85704. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85705. var index = 0;
  85706. for (var y = 0; y < height; y++) {
  85707. for (var x = 0; x < width; x++) {
  85708. var srcPos = (x + y * width) * 4;
  85709. destArray[index] = srcData[srcPos];
  85710. destArray[index + 1] = srcData[srcPos + 1];
  85711. destArray[index + 2] = srcData[srcPos + 2];
  85712. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85713. index += 4;
  85714. }
  85715. }
  85716. return destArray;
  85717. }
  85718. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85719. };
  85720. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85721. if (DDSTools.StoreLODInAlphaChannel) {
  85722. var destArray = new Float32Array(dataLength);
  85723. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85724. var index = 0;
  85725. for (var y = 0; y < height; y++) {
  85726. for (var x = 0; x < width; x++) {
  85727. var srcPos = (x + y * width) * 4;
  85728. destArray[index] = srcData[srcPos];
  85729. destArray[index + 1] = srcData[srcPos + 1];
  85730. destArray[index + 2] = srcData[srcPos + 2];
  85731. destArray[index + 3] = lod;
  85732. index += 4;
  85733. }
  85734. }
  85735. return destArray;
  85736. }
  85737. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85738. };
  85739. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85740. var destArray = new Uint8Array(dataLength);
  85741. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85742. var index = 0;
  85743. for (var y = 0; y < height; y++) {
  85744. for (var x = 0; x < width; x++) {
  85745. var srcPos = (x + y * width) * 4;
  85746. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85747. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85748. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85749. if (DDSTools.StoreLODInAlphaChannel) {
  85750. destArray[index + 3] = lod;
  85751. }
  85752. else {
  85753. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85754. }
  85755. index += 4;
  85756. }
  85757. }
  85758. return destArray;
  85759. };
  85760. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85761. var destArray = new Uint8Array(dataLength);
  85762. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85763. var index = 0;
  85764. for (var y = 0; y < height; y++) {
  85765. for (var x = 0; x < width; x++) {
  85766. var srcPos = (x + y * width) * 4;
  85767. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85768. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85769. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85770. if (DDSTools.StoreLODInAlphaChannel) {
  85771. destArray[index + 3] = lod;
  85772. }
  85773. else {
  85774. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85775. }
  85776. index += 4;
  85777. }
  85778. }
  85779. return destArray;
  85780. };
  85781. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85782. var byteArray = new Uint8Array(dataLength);
  85783. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85784. var index = 0;
  85785. for (var y = 0; y < height; y++) {
  85786. for (var x = 0; x < width; x++) {
  85787. var srcPos = (x + y * width) * 4;
  85788. byteArray[index] = srcData[srcPos + rOffset];
  85789. byteArray[index + 1] = srcData[srcPos + gOffset];
  85790. byteArray[index + 2] = srcData[srcPos + bOffset];
  85791. byteArray[index + 3] = srcData[srcPos + aOffset];
  85792. index += 4;
  85793. }
  85794. }
  85795. return byteArray;
  85796. };
  85797. DDSTools._ExtractLongWordOrder = function (value) {
  85798. if (value === 0 || value === 255 || value === -16777216) {
  85799. return 0;
  85800. }
  85801. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85802. };
  85803. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85804. var byteArray = new Uint8Array(dataLength);
  85805. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85806. var index = 0;
  85807. for (var y = 0; y < height; y++) {
  85808. for (var x = 0; x < width; x++) {
  85809. var srcPos = (x + y * width) * 3;
  85810. byteArray[index] = srcData[srcPos + rOffset];
  85811. byteArray[index + 1] = srcData[srcPos + gOffset];
  85812. byteArray[index + 2] = srcData[srcPos + bOffset];
  85813. index += 3;
  85814. }
  85815. }
  85816. return byteArray;
  85817. };
  85818. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85819. var byteArray = new Uint8Array(dataLength);
  85820. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85821. var index = 0;
  85822. for (var y = 0; y < height; y++) {
  85823. for (var x = 0; x < width; x++) {
  85824. var srcPos = (x + y * width);
  85825. byteArray[index] = srcData[srcPos];
  85826. index++;
  85827. }
  85828. }
  85829. return byteArray;
  85830. };
  85831. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85832. if (lodIndex === void 0) { lodIndex = -1; }
  85833. var sphericalPolynomialFaces = null;
  85834. if (info.sphericalPolynomial) {
  85835. sphericalPolynomialFaces = new Array();
  85836. }
  85837. var ext = engine.getCaps().s3tc;
  85838. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85839. var fourCC, width, height, dataLength = 0, dataOffset;
  85840. var byteArray, mipmapCount, mip;
  85841. var internalFormat = 0;
  85842. var format = 0;
  85843. var blockBytes = 1;
  85844. if (header[off_magic] !== DDS_MAGIC) {
  85845. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85846. return;
  85847. }
  85848. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85849. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85850. return;
  85851. }
  85852. if (info.isCompressed && !ext) {
  85853. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85854. return;
  85855. }
  85856. var bpp = header[off_RGBbpp];
  85857. dataOffset = header[off_size] + 4;
  85858. var computeFormats = false;
  85859. if (info.isFourCC) {
  85860. fourCC = header[off_pfFourCC];
  85861. switch (fourCC) {
  85862. case FOURCC_DXT1:
  85863. blockBytes = 8;
  85864. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85865. break;
  85866. case FOURCC_DXT3:
  85867. blockBytes = 16;
  85868. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85869. break;
  85870. case FOURCC_DXT5:
  85871. blockBytes = 16;
  85872. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85873. break;
  85874. case FOURCC_D3DFMT_R16G16B16A16F:
  85875. computeFormats = true;
  85876. break;
  85877. case FOURCC_D3DFMT_R32G32B32A32F:
  85878. computeFormats = true;
  85879. break;
  85880. case FOURCC_DX10:
  85881. // There is an additionnal header so dataOffset need to be changed
  85882. dataOffset += 5 * 4; // 5 uints
  85883. var supported = false;
  85884. switch (info.dxgiFormat) {
  85885. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85886. computeFormats = true;
  85887. supported = true;
  85888. break;
  85889. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85890. info.isRGB = true;
  85891. info.isFourCC = false;
  85892. bpp = 32;
  85893. supported = true;
  85894. break;
  85895. }
  85896. if (supported) {
  85897. break;
  85898. }
  85899. default:
  85900. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85901. return;
  85902. }
  85903. }
  85904. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85905. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85906. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85907. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85908. if (computeFormats) {
  85909. format = engine._getWebGLTextureType(info.textureType);
  85910. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85911. }
  85912. mipmapCount = 1;
  85913. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85914. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85915. }
  85916. for (var face = 0; face < faces; face++) {
  85917. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85918. width = header[off_width];
  85919. height = header[off_height];
  85920. for (mip = 0; mip < mipmapCount; ++mip) {
  85921. if (lodIndex === -1 || lodIndex === mip) {
  85922. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85923. var i = (lodIndex === -1) ? mip : 0;
  85924. if (!info.isCompressed && info.isFourCC) {
  85925. dataLength = width * height * 4;
  85926. var floatArray = null;
  85927. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85928. if (bpp === 128) {
  85929. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85930. if (sphericalPolynomialFaces && i == 0) {
  85931. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85932. }
  85933. }
  85934. else if (bpp === 64) {
  85935. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85936. if (sphericalPolynomialFaces && i == 0) {
  85937. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85938. }
  85939. }
  85940. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85941. format = engine._getWebGLTextureType(info.textureType);
  85942. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85943. }
  85944. else {
  85945. if (bpp === 128) {
  85946. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85947. if (sphericalPolynomialFaces && i == 0) {
  85948. sphericalPolynomialFaces.push(floatArray);
  85949. }
  85950. }
  85951. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85952. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85953. if (sphericalPolynomialFaces && i == 0) {
  85954. sphericalPolynomialFaces.push(floatArray);
  85955. }
  85956. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85957. format = engine._getWebGLTextureType(info.textureType);
  85958. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85959. }
  85960. else { // 64
  85961. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85962. if (sphericalPolynomialFaces && i == 0) {
  85963. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85964. }
  85965. }
  85966. }
  85967. if (floatArray) {
  85968. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85969. }
  85970. }
  85971. else if (info.isRGB) {
  85972. if (bpp === 24) {
  85973. dataLength = width * height * 3;
  85974. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85975. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85976. }
  85977. else { // 32
  85978. dataLength = width * height * 4;
  85979. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85980. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85981. }
  85982. }
  85983. else if (info.isLuminance) {
  85984. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85985. var unpaddedRowSize = width;
  85986. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85987. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85988. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85989. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85990. }
  85991. else {
  85992. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85993. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85994. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85995. }
  85996. }
  85997. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85998. width *= 0.5;
  85999. height *= 0.5;
  86000. width = Math.max(1.0, width);
  86001. height = Math.max(1.0, height);
  86002. }
  86003. if (currentFace !== undefined) {
  86004. // Loading a single face
  86005. break;
  86006. }
  86007. }
  86008. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86009. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86010. size: header[off_width],
  86011. right: sphericalPolynomialFaces[0],
  86012. left: sphericalPolynomialFaces[1],
  86013. up: sphericalPolynomialFaces[2],
  86014. down: sphericalPolynomialFaces[3],
  86015. front: sphericalPolynomialFaces[4],
  86016. back: sphericalPolynomialFaces[5],
  86017. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86018. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86019. gammaSpace: false,
  86020. });
  86021. }
  86022. else {
  86023. info.sphericalPolynomial = undefined;
  86024. }
  86025. };
  86026. DDSTools.StoreLODInAlphaChannel = false;
  86027. return DDSTools;
  86028. }());
  86029. BABYLON.DDSTools = DDSTools;
  86030. })(BABYLON || (BABYLON = {}));
  86031. //# sourceMappingURL=babylon.dds.js.map
  86032. var BABYLON;
  86033. (function (BABYLON) {
  86034. /**
  86035. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86036. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86037. */
  86038. var KhronosTextureContainer = /** @class */ (function () {
  86039. /**
  86040. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86041. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86042. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86043. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86044. */
  86045. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86046. this.arrayBuffer = arrayBuffer;
  86047. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86048. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86049. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86050. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86051. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86052. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86053. BABYLON.Tools.Error("texture missing KTX identifier");
  86054. return;
  86055. }
  86056. // load the reset of the header in native 32 bit int
  86057. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86058. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86059. var oppositeEndianess = header[0] === 0x01020304;
  86060. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86061. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86062. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86063. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86064. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86065. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86066. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86067. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86068. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86069. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86070. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86071. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86072. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86073. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86074. if (this.glType !== 0) {
  86075. BABYLON.Tools.Error("only compressed formats currently supported");
  86076. return;
  86077. }
  86078. else {
  86079. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86080. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86081. }
  86082. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86083. BABYLON.Tools.Error("only 2D textures currently supported");
  86084. return;
  86085. }
  86086. if (this.numberOfArrayElements !== 0) {
  86087. BABYLON.Tools.Error("texture arrays not currently supported");
  86088. return;
  86089. }
  86090. if (this.numberOfFaces !== facesExpected) {
  86091. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86092. return;
  86093. }
  86094. // we now have a completely validated file, so could use existence of loadType as success
  86095. // would need to make this more elaborate & adjust checks above to support more than one load type
  86096. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86097. }
  86098. // not as fast hardware based, but will probably never need to use
  86099. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86100. return ((val & 0xFF) << 24)
  86101. | ((val & 0xFF00) << 8)
  86102. | ((val >> 8) & 0xFF00)
  86103. | ((val >> 24) & 0xFF);
  86104. };
  86105. /**
  86106. * It is assumed that the texture has already been created & is currently bound
  86107. */
  86108. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86109. switch (this.loadType) {
  86110. case KhronosTextureContainer.COMPRESSED_2D:
  86111. this._upload2DCompressedLevels(gl, loadMipmaps);
  86112. break;
  86113. case KhronosTextureContainer.TEX_2D:
  86114. case KhronosTextureContainer.COMPRESSED_3D:
  86115. case KhronosTextureContainer.TEX_3D:
  86116. }
  86117. };
  86118. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86119. // initialize width & height for level 1
  86120. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86121. var width = this.pixelWidth;
  86122. var height = this.pixelHeight;
  86123. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86124. for (var level = 0; level < mipmapCount; level++) {
  86125. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86126. for (var face = 0; face < this.numberOfFaces; face++) {
  86127. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86128. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86129. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86130. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86131. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86132. }
  86133. width = Math.max(1.0, width * 0.5);
  86134. height = Math.max(1.0, height * 0.5);
  86135. }
  86136. };
  86137. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86138. // load types
  86139. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86140. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86141. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86142. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86143. return KhronosTextureContainer;
  86144. }());
  86145. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86146. })(BABYLON || (BABYLON = {}));
  86147. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86148. var BABYLON;
  86149. (function (BABYLON) {
  86150. var Debug;
  86151. (function (Debug) {
  86152. /**
  86153. * Class used to render a debug view of a given skeleton
  86154. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86155. */
  86156. var SkeletonViewer = /** @class */ (function () {
  86157. /**
  86158. * Creates a new SkeletonViewer
  86159. * @param skeleton defines the skeleton to render
  86160. * @param mesh defines the mesh attached to the skeleton
  86161. * @param scene defines the hosting scene
  86162. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86163. * @param renderingGroupId defines the rendering group id to use with the viewer
  86164. */
  86165. function SkeletonViewer(
  86166. /** defines the skeleton to render */
  86167. skeleton,
  86168. /** defines the mesh attached to the skeleton */
  86169. mesh, scene,
  86170. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86171. autoUpdateBonesMatrices,
  86172. /** defines the rendering group id to use with the viewer */
  86173. renderingGroupId) {
  86174. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86175. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86176. this.skeleton = skeleton;
  86177. this.mesh = mesh;
  86178. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86179. this.renderingGroupId = renderingGroupId;
  86180. /** Gets or sets the color used to render the skeleton */
  86181. this.color = BABYLON.Color3.White();
  86182. this._debugLines = new Array();
  86183. this._isEnabled = false;
  86184. this._scene = scene;
  86185. this.update();
  86186. this._renderFunction = this.update.bind(this);
  86187. }
  86188. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86189. get: function () {
  86190. return this._isEnabled;
  86191. },
  86192. /** Gets or sets a boolean indicating if the viewer is enabled */
  86193. set: function (value) {
  86194. if (this._isEnabled === value) {
  86195. return;
  86196. }
  86197. this._isEnabled = value;
  86198. if (value) {
  86199. this._scene.registerBeforeRender(this._renderFunction);
  86200. }
  86201. else {
  86202. this._scene.unregisterBeforeRender(this._renderFunction);
  86203. }
  86204. },
  86205. enumerable: true,
  86206. configurable: true
  86207. });
  86208. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86209. if (x === void 0) { x = 0; }
  86210. if (y === void 0) { y = 0; }
  86211. if (z === void 0) { z = 0; }
  86212. var tmat = BABYLON.Tmp.Matrix[0];
  86213. var parentBone = bone.getParent();
  86214. tmat.copyFrom(bone.getLocalMatrix());
  86215. if (x !== 0 || y !== 0 || z !== 0) {
  86216. var tmat2 = BABYLON.Tmp.Matrix[1];
  86217. BABYLON.Matrix.IdentityToRef(tmat2);
  86218. tmat2.m[12] = x;
  86219. tmat2.m[13] = y;
  86220. tmat2.m[14] = z;
  86221. tmat2.multiplyToRef(tmat, tmat);
  86222. }
  86223. if (parentBone) {
  86224. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86225. }
  86226. tmat.multiplyToRef(meshMat, tmat);
  86227. position.x = tmat.m[12];
  86228. position.y = tmat.m[13];
  86229. position.z = tmat.m[14];
  86230. };
  86231. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86232. var len = bones.length;
  86233. var meshPos = this.mesh.position;
  86234. for (var i = 0; i < len; i++) {
  86235. var bone = bones[i];
  86236. var points = this._debugLines[i];
  86237. if (!points) {
  86238. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86239. this._debugLines[i] = points;
  86240. }
  86241. this._getBonePosition(points[0], bone, meshMat);
  86242. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86243. points[0].subtractInPlace(meshPos);
  86244. points[1].subtractInPlace(meshPos);
  86245. }
  86246. };
  86247. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86248. var len = bones.length;
  86249. var boneNum = 0;
  86250. var meshPos = this.mesh.position;
  86251. for (var i = len - 1; i >= 0; i--) {
  86252. var childBone = bones[i];
  86253. var parentBone = childBone.getParent();
  86254. if (!parentBone) {
  86255. continue;
  86256. }
  86257. var points = this._debugLines[boneNum];
  86258. if (!points) {
  86259. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86260. this._debugLines[boneNum] = points;
  86261. }
  86262. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86263. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86264. points[0].subtractInPlace(meshPos);
  86265. points[1].subtractInPlace(meshPos);
  86266. boneNum++;
  86267. }
  86268. };
  86269. /** Update the viewer to sync with current skeleton state */
  86270. SkeletonViewer.prototype.update = function () {
  86271. if (this.autoUpdateBonesMatrices) {
  86272. this.skeleton.computeAbsoluteTransforms();
  86273. }
  86274. if (this.skeleton.bones[0].length === undefined) {
  86275. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86276. }
  86277. else {
  86278. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86279. }
  86280. if (!this._debugMesh) {
  86281. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86282. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86283. }
  86284. else {
  86285. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86286. }
  86287. this._debugMesh.position.copyFrom(this.mesh.position);
  86288. this._debugMesh.color = this.color;
  86289. };
  86290. /** Release associated resources */
  86291. SkeletonViewer.prototype.dispose = function () {
  86292. if (this._debugMesh) {
  86293. this.isEnabled = false;
  86294. this._debugMesh.dispose();
  86295. this._debugMesh = null;
  86296. }
  86297. };
  86298. return SkeletonViewer;
  86299. }());
  86300. Debug.SkeletonViewer = SkeletonViewer;
  86301. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86302. })(BABYLON || (BABYLON = {}));
  86303. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86304. /**
  86305. * Module Debug contains the (visual) components to debug a scene correctly
  86306. */
  86307. var BABYLON;
  86308. (function (BABYLON) {
  86309. var Debug;
  86310. (function (Debug) {
  86311. /**
  86312. * The Axes viewer will show 3 axes in a specific point in space
  86313. */
  86314. var AxesViewer = /** @class */ (function () {
  86315. /**
  86316. * Creates a new AxesViewer
  86317. * @param scene defines the hosting scene
  86318. * @param scaleLines defines a number used to scale line length (1 by default)
  86319. */
  86320. function AxesViewer(scene, scaleLines) {
  86321. if (scaleLines === void 0) { scaleLines = 1; }
  86322. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86323. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86324. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86325. /**
  86326. * Gets or sets a number used to scale line length
  86327. */
  86328. this.scaleLines = 1;
  86329. this.scaleLines = scaleLines;
  86330. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86331. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86332. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86333. this._xmesh.renderingGroupId = 2;
  86334. this._ymesh.renderingGroupId = 2;
  86335. this._zmesh.renderingGroupId = 2;
  86336. this._xmesh.material.checkReadyOnlyOnce = true;
  86337. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86338. this._ymesh.material.checkReadyOnlyOnce = true;
  86339. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86340. this._zmesh.material.checkReadyOnlyOnce = true;
  86341. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86342. this.scene = scene;
  86343. }
  86344. /**
  86345. * Force the viewer to update
  86346. * @param position defines the position of the viewer
  86347. * @param xaxis defines the x axis of the viewer
  86348. * @param yaxis defines the y axis of the viewer
  86349. * @param zaxis defines the z axis of the viewer
  86350. */
  86351. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86352. var scaleLines = this.scaleLines;
  86353. if (this._xmesh) {
  86354. this._xmesh.position.copyFrom(position);
  86355. }
  86356. if (this._ymesh) {
  86357. this._ymesh.position.copyFrom(position);
  86358. }
  86359. if (this._zmesh) {
  86360. this._zmesh.position.copyFrom(position);
  86361. }
  86362. var point2 = this._xline[1];
  86363. point2.x = xaxis.x * scaleLines;
  86364. point2.y = xaxis.y * scaleLines;
  86365. point2.z = xaxis.z * scaleLines;
  86366. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86367. point2 = this._yline[1];
  86368. point2.x = yaxis.x * scaleLines;
  86369. point2.y = yaxis.y * scaleLines;
  86370. point2.z = yaxis.z * scaleLines;
  86371. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86372. point2 = this._zline[1];
  86373. point2.x = zaxis.x * scaleLines;
  86374. point2.y = zaxis.y * scaleLines;
  86375. point2.z = zaxis.z * scaleLines;
  86376. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86377. };
  86378. /** Releases resources */
  86379. AxesViewer.prototype.dispose = function () {
  86380. if (this._xmesh) {
  86381. this._xmesh.dispose();
  86382. }
  86383. if (this._ymesh) {
  86384. this._ymesh.dispose();
  86385. }
  86386. if (this._zmesh) {
  86387. this._zmesh.dispose();
  86388. }
  86389. this._xmesh = null;
  86390. this._ymesh = null;
  86391. this._zmesh = null;
  86392. this.scene = null;
  86393. };
  86394. return AxesViewer;
  86395. }());
  86396. Debug.AxesViewer = AxesViewer;
  86397. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86398. })(BABYLON || (BABYLON = {}));
  86399. //# sourceMappingURL=babylon.axesViewer.js.map
  86400. var BABYLON;
  86401. (function (BABYLON) {
  86402. var Debug;
  86403. (function (Debug) {
  86404. /**
  86405. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86406. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86407. */
  86408. var BoneAxesViewer = /** @class */ (function (_super) {
  86409. __extends(BoneAxesViewer, _super);
  86410. /**
  86411. * Creates a new BoneAxesViewer
  86412. * @param scene defines the hosting scene
  86413. * @param bone defines the target bone
  86414. * @param mesh defines the target mesh
  86415. * @param scaleLines defines a scaling factor for line length (1 by default)
  86416. */
  86417. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86418. if (scaleLines === void 0) { scaleLines = 1; }
  86419. var _this = _super.call(this, scene, scaleLines) || this;
  86420. /** Gets current position */
  86421. _this.pos = BABYLON.Vector3.Zero();
  86422. /** Gets direction of X axis */
  86423. _this.xaxis = BABYLON.Vector3.Zero();
  86424. /** Gets direction of Y axis */
  86425. _this.yaxis = BABYLON.Vector3.Zero();
  86426. /** Gets direction of Z axis */
  86427. _this.zaxis = BABYLON.Vector3.Zero();
  86428. _this.mesh = mesh;
  86429. _this.bone = bone;
  86430. return _this;
  86431. }
  86432. /**
  86433. * Force the viewer to update
  86434. */
  86435. BoneAxesViewer.prototype.update = function () {
  86436. if (!this.mesh || !this.bone) {
  86437. return;
  86438. }
  86439. var bone = this.bone;
  86440. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86441. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86442. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86443. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86444. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86445. };
  86446. /** Releases resources */
  86447. BoneAxesViewer.prototype.dispose = function () {
  86448. if (this.mesh) {
  86449. this.mesh = null;
  86450. this.bone = null;
  86451. _super.prototype.dispose.call(this);
  86452. }
  86453. };
  86454. return BoneAxesViewer;
  86455. }(Debug.AxesViewer));
  86456. Debug.BoneAxesViewer = BoneAxesViewer;
  86457. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86458. })(BABYLON || (BABYLON = {}));
  86459. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86460. var BABYLON;
  86461. (function (BABYLON) {
  86462. var RayHelper = /** @class */ (function () {
  86463. function RayHelper(ray) {
  86464. this.ray = ray;
  86465. }
  86466. RayHelper.CreateAndShow = function (ray, scene, color) {
  86467. var helper = new RayHelper(ray);
  86468. helper.show(scene, color);
  86469. return helper;
  86470. };
  86471. RayHelper.prototype.show = function (scene, color) {
  86472. if (!this._renderFunction && this.ray) {
  86473. var ray = this.ray;
  86474. this._renderFunction = this._render.bind(this);
  86475. this._scene = scene;
  86476. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86477. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86478. if (this._renderFunction) {
  86479. this._scene.registerBeforeRender(this._renderFunction);
  86480. }
  86481. }
  86482. if (color && this._renderLine) {
  86483. this._renderLine.color.copyFrom(color);
  86484. }
  86485. };
  86486. RayHelper.prototype.hide = function () {
  86487. if (this._renderFunction && this._scene) {
  86488. this._scene.unregisterBeforeRender(this._renderFunction);
  86489. this._scene = null;
  86490. this._renderFunction = null;
  86491. if (this._renderLine) {
  86492. this._renderLine.dispose();
  86493. this._renderLine = null;
  86494. }
  86495. this._renderPoints = [];
  86496. }
  86497. };
  86498. RayHelper.prototype._render = function () {
  86499. var ray = this.ray;
  86500. if (!ray) {
  86501. return;
  86502. }
  86503. var point = this._renderPoints[1];
  86504. var len = Math.min(ray.length, 1000000);
  86505. point.copyFrom(ray.direction);
  86506. point.scaleInPlace(len);
  86507. point.addInPlace(ray.origin);
  86508. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86509. };
  86510. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86511. this._attachedToMesh = mesh;
  86512. var ray = this.ray;
  86513. if (!ray) {
  86514. return;
  86515. }
  86516. if (!ray.direction) {
  86517. ray.direction = BABYLON.Vector3.Zero();
  86518. }
  86519. if (!ray.origin) {
  86520. ray.origin = BABYLON.Vector3.Zero();
  86521. }
  86522. if (length) {
  86523. ray.length = length;
  86524. }
  86525. if (!meshSpaceOrigin) {
  86526. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86527. }
  86528. if (!meshSpaceDirection) {
  86529. // -1 so that this will work with Mesh.lookAt
  86530. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86531. }
  86532. if (!this._meshSpaceDirection) {
  86533. this._meshSpaceDirection = meshSpaceDirection.clone();
  86534. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86535. }
  86536. else {
  86537. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86538. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86539. }
  86540. if (!this._updateToMeshFunction) {
  86541. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86542. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86543. }
  86544. this._updateToMesh();
  86545. };
  86546. RayHelper.prototype.detachFromMesh = function () {
  86547. if (this._attachedToMesh) {
  86548. if (this._updateToMeshFunction) {
  86549. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86550. }
  86551. this._attachedToMesh = null;
  86552. this._updateToMeshFunction = null;
  86553. }
  86554. };
  86555. RayHelper.prototype._updateToMesh = function () {
  86556. var ray = this.ray;
  86557. if (!this._attachedToMesh || !ray) {
  86558. return;
  86559. }
  86560. if (this._attachedToMesh._isDisposed) {
  86561. this.detachFromMesh();
  86562. return;
  86563. }
  86564. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86565. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86566. };
  86567. RayHelper.prototype.dispose = function () {
  86568. this.hide();
  86569. this.detachFromMesh();
  86570. this.ray = null;
  86571. };
  86572. return RayHelper;
  86573. }());
  86574. BABYLON.RayHelper = RayHelper;
  86575. })(BABYLON || (BABYLON = {}));
  86576. //# sourceMappingURL=babylon.rayHelper.js.map
  86577. var BABYLON;
  86578. (function (BABYLON) {
  86579. // load the inspector using require, if not present in the global namespace.
  86580. var DebugLayer = /** @class */ (function () {
  86581. function DebugLayer(scene) {
  86582. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86583. this._scene = scene;
  86584. // load inspector using require, if it doesn't exist on the global namespace.
  86585. }
  86586. /** Creates the inspector window. */
  86587. DebugLayer.prototype._createInspector = function (config) {
  86588. if (config === void 0) { config = {}; }
  86589. var popup = config.popup || false;
  86590. var initialTab = config.initialTab || 0;
  86591. var parentElement = config.parentElement || null;
  86592. if (!this._inspector) {
  86593. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86594. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86595. } // else nothing to do,; instance is already existing
  86596. };
  86597. DebugLayer.prototype.isVisible = function () {
  86598. if (!this._inspector) {
  86599. return false;
  86600. }
  86601. return true;
  86602. };
  86603. DebugLayer.prototype.hide = function () {
  86604. if (this._inspector) {
  86605. try {
  86606. this._inspector.dispose();
  86607. }
  86608. catch (e) {
  86609. // If the inspector has been removed directly from the inspector tool
  86610. }
  86611. this._inspector = null;
  86612. }
  86613. };
  86614. /**
  86615. *
  86616. * Launch the debugLayer.
  86617. *
  86618. * initialTab:
  86619. * | Value | Tab Name |
  86620. * | --- | --- |
  86621. * | 0 | Scene |
  86622. * | 1 | Console |
  86623. * | 2 | Stats |
  86624. * | 3 | Textures |
  86625. * | 4 | Mesh |
  86626. * | 5 | Light |
  86627. * | 6 | Material |
  86628. * | 7 | GLTF |
  86629. * | 8 | GUI |
  86630. * | 9 | Physics |
  86631. * | 10 | Camera |
  86632. * | 11 | Audio |
  86633. *
  86634. */
  86635. DebugLayer.prototype.show = function (config) {
  86636. if (config === void 0) { config = {}; }
  86637. if (typeof this.BJSINSPECTOR == 'undefined') {
  86638. // Load inspector and add it to the DOM
  86639. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86640. }
  86641. else {
  86642. // Otherwise creates the inspector
  86643. this._createInspector(config);
  86644. }
  86645. };
  86646. /**
  86647. * Gets the active tab
  86648. * @return the index of the active tab or -1 if the inspector is hidden
  86649. */
  86650. DebugLayer.prototype.getActiveTab = function () {
  86651. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86652. };
  86653. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86654. return DebugLayer;
  86655. }());
  86656. BABYLON.DebugLayer = DebugLayer;
  86657. })(BABYLON || (BABYLON = {}));
  86658. //# sourceMappingURL=babylon.debugLayer.js.map
  86659. var BABYLON;
  86660. (function (BABYLON) {
  86661. var Debug;
  86662. (function (Debug) {
  86663. /**
  86664. * Used to show the physics impostor around the specific mesh
  86665. */
  86666. var PhysicsViewer = /** @class */ (function () {
  86667. /**
  86668. * Creates a new PhysicsViewer
  86669. * @param scene defines the hosting scene
  86670. */
  86671. function PhysicsViewer(scene) {
  86672. /** @hidden */
  86673. this._impostors = [];
  86674. /** @hidden */
  86675. this._meshes = [];
  86676. /** @hidden */
  86677. this._numMeshes = 0;
  86678. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86679. var physicEngine = this._scene.getPhysicsEngine();
  86680. if (physicEngine) {
  86681. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86682. }
  86683. }
  86684. /** @hidden */
  86685. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86686. var plugin = this._physicsEnginePlugin;
  86687. for (var i = 0; i < this._numMeshes; i++) {
  86688. var impostor = this._impostors[i];
  86689. if (!impostor) {
  86690. continue;
  86691. }
  86692. if (impostor.isDisposed) {
  86693. this.hideImpostor(this._impostors[i--]);
  86694. }
  86695. else {
  86696. var mesh = this._meshes[i];
  86697. if (mesh && plugin) {
  86698. plugin.syncMeshWithImpostor(mesh, impostor);
  86699. }
  86700. }
  86701. }
  86702. };
  86703. /**
  86704. * Renders a specified physic impostor
  86705. * @param impostor defines the impostor to render
  86706. */
  86707. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86708. if (!this._scene) {
  86709. return;
  86710. }
  86711. for (var i = 0; i < this._numMeshes; i++) {
  86712. if (this._impostors[i] == impostor) {
  86713. return;
  86714. }
  86715. }
  86716. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86717. if (debugMesh) {
  86718. this._impostors[this._numMeshes] = impostor;
  86719. this._meshes[this._numMeshes] = debugMesh;
  86720. if (this._numMeshes === 0) {
  86721. this._renderFunction = this._updateDebugMeshes.bind(this);
  86722. this._scene.registerBeforeRender(this._renderFunction);
  86723. }
  86724. this._numMeshes++;
  86725. }
  86726. };
  86727. /**
  86728. * Hides a specified physic impostor
  86729. * @param impostor defines the impostor to hide
  86730. */
  86731. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86732. if (!impostor || !this._scene) {
  86733. return;
  86734. }
  86735. var removed = false;
  86736. for (var i = 0; i < this._numMeshes; i++) {
  86737. if (this._impostors[i] == impostor) {
  86738. var mesh = this._meshes[i];
  86739. if (!mesh) {
  86740. continue;
  86741. }
  86742. this._scene.removeMesh(mesh);
  86743. mesh.dispose();
  86744. this._numMeshes--;
  86745. if (this._numMeshes > 0) {
  86746. this._meshes[i] = this._meshes[this._numMeshes];
  86747. this._impostors[i] = this._impostors[this._numMeshes];
  86748. this._meshes[this._numMeshes] = null;
  86749. this._impostors[this._numMeshes] = null;
  86750. }
  86751. else {
  86752. this._meshes[0] = null;
  86753. this._impostors[0] = null;
  86754. }
  86755. removed = true;
  86756. break;
  86757. }
  86758. }
  86759. if (removed && this._numMeshes === 0) {
  86760. this._scene.unregisterBeforeRender(this._renderFunction);
  86761. }
  86762. };
  86763. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86764. if (!this._debugMaterial) {
  86765. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86766. this._debugMaterial.wireframe = true;
  86767. }
  86768. return this._debugMaterial;
  86769. };
  86770. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86771. if (!this._debugBoxMesh) {
  86772. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86773. this._debugBoxMesh.renderingGroupId = 1;
  86774. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86775. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86776. scene.removeMesh(this._debugBoxMesh);
  86777. }
  86778. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86779. };
  86780. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86781. if (!this._debugSphereMesh) {
  86782. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86783. this._debugSphereMesh.renderingGroupId = 1;
  86784. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86785. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86786. scene.removeMesh(this._debugSphereMesh);
  86787. }
  86788. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86789. };
  86790. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86791. var mesh = null;
  86792. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86793. mesh = this._getDebugBoxMesh(scene);
  86794. impostor.getBoxSizeToRef(mesh.scaling);
  86795. }
  86796. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86797. mesh = this._getDebugSphereMesh(scene);
  86798. var radius = impostor.getRadius();
  86799. mesh.scaling.x = radius * 2;
  86800. mesh.scaling.y = radius * 2;
  86801. mesh.scaling.z = radius * 2;
  86802. }
  86803. return mesh;
  86804. };
  86805. /** Releases all resources */
  86806. PhysicsViewer.prototype.dispose = function () {
  86807. for (var i = 0; i < this._numMeshes; i++) {
  86808. this.hideImpostor(this._impostors[i]);
  86809. }
  86810. if (this._debugBoxMesh) {
  86811. this._debugBoxMesh.dispose();
  86812. }
  86813. if (this._debugSphereMesh) {
  86814. this._debugSphereMesh.dispose();
  86815. }
  86816. if (this._debugMaterial) {
  86817. this._debugMaterial.dispose();
  86818. }
  86819. this._impostors.length = 0;
  86820. this._scene = null;
  86821. this._physicsEnginePlugin = null;
  86822. };
  86823. return PhysicsViewer;
  86824. }());
  86825. Debug.PhysicsViewer = PhysicsViewer;
  86826. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86827. })(BABYLON || (BABYLON = {}));
  86828. //# sourceMappingURL=babylon.physicsViewer.js.map
  86829. var BABYLON;
  86830. (function (BABYLON) {
  86831. var BoundingBoxRenderer = /** @class */ (function () {
  86832. function BoundingBoxRenderer(scene) {
  86833. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86834. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86835. this.showBackLines = true;
  86836. this.renderList = new BABYLON.SmartArray(32);
  86837. this._vertexBuffers = {};
  86838. this._scene = scene;
  86839. }
  86840. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86841. if (this._colorShader) {
  86842. return;
  86843. }
  86844. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86845. attributes: [BABYLON.VertexBuffer.PositionKind],
  86846. uniforms: ["world", "viewProjection", "color"]
  86847. });
  86848. var engine = this._scene.getEngine();
  86849. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86851. this._createIndexBuffer();
  86852. };
  86853. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86854. var engine = this._scene.getEngine();
  86855. 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]);
  86856. };
  86857. BoundingBoxRenderer.prototype._rebuild = function () {
  86858. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86859. if (vb) {
  86860. vb._rebuild();
  86861. }
  86862. this._createIndexBuffer();
  86863. };
  86864. BoundingBoxRenderer.prototype.reset = function () {
  86865. this.renderList.reset();
  86866. };
  86867. BoundingBoxRenderer.prototype.render = function () {
  86868. if (this.renderList.length === 0) {
  86869. return;
  86870. }
  86871. this._prepareRessources();
  86872. if (!this._colorShader.isReady()) {
  86873. return;
  86874. }
  86875. var engine = this._scene.getEngine();
  86876. engine.setDepthWrite(false);
  86877. this._colorShader._preBind();
  86878. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86879. var boundingBox = this.renderList.data[boundingBoxIndex];
  86880. var min = boundingBox.minimum;
  86881. var max = boundingBox.maximum;
  86882. var diff = max.subtract(min);
  86883. var median = min.add(diff.scale(0.5));
  86884. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86885. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86886. .multiply(boundingBox.getWorldMatrix());
  86887. // VBOs
  86888. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86889. if (this.showBackLines) {
  86890. // Back
  86891. engine.setDepthFunctionToGreaterOrEqual();
  86892. this._scene.resetCachedMaterial();
  86893. this._colorShader.setColor4("color", this.backColor.toColor4());
  86894. this._colorShader.bind(worldMatrix);
  86895. // Draw order
  86896. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86897. }
  86898. // Front
  86899. engine.setDepthFunctionToLess();
  86900. this._scene.resetCachedMaterial();
  86901. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86902. this._colorShader.bind(worldMatrix);
  86903. // Draw order
  86904. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86905. }
  86906. this._colorShader.unbind();
  86907. engine.setDepthFunctionToLessOrEqual();
  86908. engine.setDepthWrite(true);
  86909. };
  86910. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86911. this._prepareRessources();
  86912. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86913. return;
  86914. }
  86915. var engine = this._scene.getEngine();
  86916. engine.setDepthWrite(false);
  86917. engine.setColorWrite(false);
  86918. this._colorShader._preBind();
  86919. var boundingBox = mesh._boundingInfo.boundingBox;
  86920. var min = boundingBox.minimum;
  86921. var max = boundingBox.maximum;
  86922. var diff = max.subtract(min);
  86923. var median = min.add(diff.scale(0.5));
  86924. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86925. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86926. .multiply(boundingBox.getWorldMatrix());
  86927. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86928. engine.setDepthFunctionToLess();
  86929. this._scene.resetCachedMaterial();
  86930. this._colorShader.bind(worldMatrix);
  86931. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86932. this._colorShader.unbind();
  86933. engine.setDepthFunctionToLessOrEqual();
  86934. engine.setDepthWrite(true);
  86935. engine.setColorWrite(true);
  86936. };
  86937. BoundingBoxRenderer.prototype.dispose = function () {
  86938. if (!this._colorShader) {
  86939. return;
  86940. }
  86941. this.renderList.dispose();
  86942. this._colorShader.dispose();
  86943. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86944. if (buffer) {
  86945. buffer.dispose();
  86946. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86947. }
  86948. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86949. };
  86950. return BoundingBoxRenderer;
  86951. }());
  86952. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86953. })(BABYLON || (BABYLON = {}));
  86954. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86955. var BABYLON;
  86956. (function (BABYLON) {
  86957. /**
  86958. * Renders a layer on top of an existing scene
  86959. */
  86960. var UtilityLayerRenderer = /** @class */ (function () {
  86961. /**
  86962. * Instantiates a UtilityLayerRenderer
  86963. * @param originalScene the original scene that will be rendered on top of
  86964. */
  86965. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86966. var _this = this;
  86967. this.originalScene = originalScene;
  86968. this._pointerCaptures = {};
  86969. this._lastPointerEvents = {};
  86970. /**
  86971. * If the utility layer should automatically be rendered on top of existing scene
  86972. */
  86973. this.shouldRender = true;
  86974. /**
  86975. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  86976. */
  86977. this.onlyCheckPointerDownEvents = true;
  86978. /**
  86979. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  86980. */
  86981. this.processAllEvents = false;
  86982. /**
  86983. * Observable raised when the pointer move from the utility layer scene to the main scene
  86984. */
  86985. this.onPointerOutObservable = new BABYLON.Observable();
  86986. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86987. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86988. originalScene.getEngine().scenes.pop();
  86989. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  86990. this.utilityLayerScene.detachControl();
  86991. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  86992. if (!_this.processAllEvents) {
  86993. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  86994. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  86995. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  86996. return;
  86997. }
  86998. }
  86999. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87000. if (!prePointerInfo.ray && utilityScenePick) {
  87001. prePointerInfo.ray = utilityScenePick.ray;
  87002. }
  87003. // always fire the prepointer oversvable
  87004. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87005. // allow every non pointer down event to flow to the utility layer
  87006. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87007. if (!prePointerInfo.skipOnPointerObservable) {
  87008. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87009. }
  87010. return;
  87011. }
  87012. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87013. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87014. if (utilityScenePick && utilityScenePick.hit) {
  87015. if (!prePointerInfo.skipOnPointerObservable) {
  87016. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87017. }
  87018. prePointerInfo.skipOnPointerObservable = true;
  87019. }
  87020. }
  87021. else {
  87022. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87023. var pointerEvent = (prePointerInfo.event);
  87024. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87025. if (originalScenePick && utilityScenePick) {
  87026. if (utilityScenePick.distance === 0) {
  87027. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87028. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87029. }
  87030. }
  87031. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87032. if (!prePointerInfo.skipOnPointerObservable) {
  87033. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87034. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87035. }
  87036. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87037. }
  87038. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87039. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87040. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87041. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87042. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87043. }
  87044. }
  87045. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87046. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87047. }
  87048. }
  87049. }
  87050. });
  87051. // Render directly on top of existing scene without clearing
  87052. this.utilityLayerScene.autoClear = false;
  87053. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87054. if (_this.shouldRender) {
  87055. _this.render();
  87056. }
  87057. });
  87058. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87059. _this.dispose();
  87060. });
  87061. this._updateCamera();
  87062. }
  87063. /**
  87064. * Renders the utility layers scene on top of the original scene
  87065. */
  87066. UtilityLayerRenderer.prototype.render = function () {
  87067. this._updateCamera();
  87068. this.utilityLayerScene.render(false);
  87069. };
  87070. /**
  87071. * Disposes of the renderer
  87072. */
  87073. UtilityLayerRenderer.prototype.dispose = function () {
  87074. this.onPointerOutObservable.clear();
  87075. if (this._afterRenderObserver) {
  87076. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87077. }
  87078. if (this._sceneDisposeObserver) {
  87079. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87080. }
  87081. if (this._originalPointerObserver) {
  87082. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87083. }
  87084. this.utilityLayerScene.dispose();
  87085. };
  87086. UtilityLayerRenderer.prototype._updateCamera = function () {
  87087. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87088. };
  87089. return UtilityLayerRenderer;
  87090. }());
  87091. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87092. })(BABYLON || (BABYLON = {}));
  87093. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87094. var BABYLON;
  87095. (function (BABYLON) {
  87096. /**
  87097. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87098. */
  87099. var PointerDragBehavior = /** @class */ (function () {
  87100. /**
  87101. * Creates a pointer drag behavior that can be attached to a mesh
  87102. * @param options The drag axis or normal of the plane that will be dragged across.
  87103. */
  87104. function PointerDragBehavior(options) {
  87105. this.options = options;
  87106. this._draggingID = -1;
  87107. /**
  87108. * Fires each time the attached mesh is dragged with the pointer
  87109. */
  87110. this.onDragObservable = new BABYLON.Observable();
  87111. /**
  87112. * Fires each time a drag begins (eg. mouse down on mesh)
  87113. */
  87114. this.onDragStartObservable = new BABYLON.Observable();
  87115. /**
  87116. * Fires each time a drag ends (eg. mouse release after drag)
  87117. */
  87118. this.onDragEndObservable = new BABYLON.Observable();
  87119. /**
  87120. * If the attached mesh should be moved when dragged
  87121. */
  87122. this.moveAttached = true;
  87123. /**
  87124. * Mesh with the position where the drag plane should be placed
  87125. */
  87126. this._dragPlaneParent = null;
  87127. /**
  87128. * If the drag behavior will react to drag events
  87129. */
  87130. this.enabled = true;
  87131. var optionCount = 0;
  87132. if (options.dragAxis) {
  87133. optionCount++;
  87134. }
  87135. if (options.dragPlaneNormal) {
  87136. optionCount++;
  87137. }
  87138. if (optionCount > 1) {
  87139. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87140. }
  87141. if (optionCount < 1) {
  87142. throw "At least one drag mode option must be specified";
  87143. }
  87144. }
  87145. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87146. /**
  87147. * The name of the behavior
  87148. */
  87149. get: function () {
  87150. return "PointerDrag";
  87151. },
  87152. enumerable: true,
  87153. configurable: true
  87154. });
  87155. /**
  87156. * Initializes the behavior
  87157. */
  87158. PointerDragBehavior.prototype.init = function () { };
  87159. /**
  87160. * Attaches the drag behavior the passed in mesh
  87161. * @param ownerNode The mesh that will be dragged around once attached
  87162. */
  87163. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87164. var _this = this;
  87165. this._scene = ownerNode.getScene();
  87166. this._attachedNode = ownerNode;
  87167. // Initialize drag plane to not interfere with existing scene
  87168. if (!PointerDragBehavior._planeScene) {
  87169. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87170. this._scene.getEngine().scenes.pop();
  87171. }
  87172. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87173. // State of the drag
  87174. var dragging = false;
  87175. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87176. var delta = new BABYLON.Vector3(0, 0, 0);
  87177. var pickPredicate = function (m) {
  87178. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87179. };
  87180. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87181. if (!_this.enabled) {
  87182. return;
  87183. }
  87184. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87185. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87186. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87187. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87188. if (pickedPoint) {
  87189. dragging = true;
  87190. _this._draggingID = pointerInfo.event.pointerId;
  87191. lastPosition.copyFrom(pickedPoint);
  87192. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87193. }
  87194. }
  87195. }
  87196. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87197. if (_this._draggingID == pointerInfo.event.pointerId) {
  87198. dragging = false;
  87199. _this._draggingID = -1;
  87200. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87201. }
  87202. }
  87203. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87204. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87205. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87206. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87207. if (pickedPoint) {
  87208. // depending on the drag mode option drag accordingly
  87209. if (_this.options.dragAxis) {
  87210. //get the closest point on the dragaxis from the selected mesh to the picked point location
  87211. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  87212. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  87213. }
  87214. else {
  87215. pickedPoint.subtractToRef(lastPosition, delta);
  87216. }
  87217. if (_this.moveAttached) {
  87218. _this._attachedNode.position.addInPlace(delta);
  87219. }
  87220. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  87221. lastPosition.copyFrom(pickedPoint);
  87222. }
  87223. }
  87224. }
  87225. });
  87226. };
  87227. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87228. var _this = this;
  87229. if (!ray) {
  87230. return null;
  87231. }
  87232. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87233. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87234. return pickResult.pickedPoint;
  87235. }
  87236. else {
  87237. return null;
  87238. }
  87239. };
  87240. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87241. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87242. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  87243. if (this.options.dragAxis) {
  87244. var camPos = ray.origin;
  87245. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87246. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  87247. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  87248. // Get perpendicular line from direction to camera and drag axis
  87249. var lineA = pointB.subtract(pointA);
  87250. var lineB = pointC.subtract(pointA);
  87251. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87252. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87253. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87254. this._dragPlane.position.copyFrom(pointA);
  87255. this._dragPlane.lookAt(pointA.add(norm));
  87256. }
  87257. else if (this.options.dragPlaneNormal) {
  87258. this._dragPlane.position.copyFrom(pointA);
  87259. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  87260. }
  87261. this._dragPlane.computeWorldMatrix(true);
  87262. };
  87263. /**
  87264. * Detaches the behavior from the mesh
  87265. */
  87266. PointerDragBehavior.prototype.detach = function () {
  87267. if (this._pointerObserver) {
  87268. this._scene.onPointerObservable.remove(this._pointerObserver);
  87269. }
  87270. };
  87271. return PointerDragBehavior;
  87272. }());
  87273. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87274. })(BABYLON || (BABYLON = {}));
  87275. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87276. var BABYLON;
  87277. (function (BABYLON) {
  87278. /**
  87279. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87280. */
  87281. var Gizmo = /** @class */ (function () {
  87282. /**
  87283. * Creates a gizmo
  87284. * @param gizmoLayer The utility layer the gizmo will be added to
  87285. */
  87286. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87287. var _this = this;
  87288. this.gizmoLayer = gizmoLayer;
  87289. this._interactionsEnabled = true;
  87290. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87291. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87292. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87293. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87294. _this._rootMesh.scaling.set(dist, dist, dist);
  87295. }
  87296. if (_this.attachedMesh) {
  87297. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87298. }
  87299. });
  87300. }
  87301. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87302. };
  87303. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87304. get: function () {
  87305. return this._interactionsEnabled;
  87306. },
  87307. /**
  87308. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87309. */
  87310. set: function (value) {
  87311. this._interactionsEnabled = value;
  87312. this._onInteractionsEnabledChanged(value);
  87313. },
  87314. enumerable: true,
  87315. configurable: true
  87316. });
  87317. /**
  87318. * Disposes of the gizmo
  87319. */
  87320. Gizmo.prototype.dispose = function () {
  87321. this._rootMesh.dispose();
  87322. if (this._beforeRenderObserver) {
  87323. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87324. }
  87325. };
  87326. return Gizmo;
  87327. }());
  87328. BABYLON.Gizmo = Gizmo;
  87329. })(BABYLON || (BABYLON = {}));
  87330. //# sourceMappingURL=babylon.gizmo.js.map
  87331. var BABYLON;
  87332. (function (BABYLON) {
  87333. /**
  87334. * Single axis drag gizmo
  87335. */
  87336. var AxisDragGizmo = /** @class */ (function (_super) {
  87337. __extends(AxisDragGizmo, _super);
  87338. /**
  87339. * Creates an AxisDragGizmo
  87340. * @param gizmoLayer The utility layer the gizmo will be added to
  87341. * @param dragAxis The axis which the gizmo will be able to drag on
  87342. * @param color The color of the gizmo
  87343. */
  87344. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87345. var _this = _super.call(this, gizmoLayer) || this;
  87346. // Create Material
  87347. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87348. coloredMaterial.disableLighting = true;
  87349. coloredMaterial.emissiveColor = color;
  87350. // Build mesh on root node
  87351. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87352. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87353. _this._rootMesh.addChild(arrowMesh);
  87354. _this._rootMesh.addChild(arrowTail);
  87355. // Position arrow pointing in its drag axis
  87356. arrowMesh.scaling.scaleInPlace(0.1);
  87357. arrowMesh.material = coloredMaterial;
  87358. arrowMesh.rotation.x = Math.PI / 2;
  87359. arrowMesh.position.z += 0.3;
  87360. arrowTail.rotation.x = Math.PI / 2;
  87361. arrowTail.material = coloredMaterial;
  87362. arrowTail.position.z += 0.2;
  87363. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87364. // Add drag behavior to handle events when the gizmo is dragged
  87365. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87366. _this._dragBehavior.moveAttached = false;
  87367. _this._rootMesh.addBehavior(_this._dragBehavior);
  87368. _this._dragBehavior.onDragObservable.add(function (event) {
  87369. if (!_this.interactionsEnabled) {
  87370. return;
  87371. }
  87372. if (_this.attachedMesh) {
  87373. _this.attachedMesh.position.addInPlace(event.delta);
  87374. }
  87375. });
  87376. return _this;
  87377. }
  87378. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87379. this._dragBehavior.enabled = value;
  87380. };
  87381. /**
  87382. * Disposes of the gizmo
  87383. */
  87384. AxisDragGizmo.prototype.dispose = function () {
  87385. this._dragBehavior.detach();
  87386. _super.prototype.dispose.call(this);
  87387. };
  87388. return AxisDragGizmo;
  87389. }(BABYLON.Gizmo));
  87390. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87391. })(BABYLON || (BABYLON = {}));
  87392. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87393. var BABYLON;
  87394. (function (BABYLON) {
  87395. /**
  87396. * Single axis scale gizmo
  87397. */
  87398. var AxisScaleGizmo = /** @class */ (function (_super) {
  87399. __extends(AxisScaleGizmo, _super);
  87400. /**
  87401. * Creates an AxisScaleGizmo
  87402. * @param gizmoLayer The utility layer the gizmo will be added to
  87403. * @param dragAxis The axis which the gizmo will be able to scale on
  87404. * @param color The color of the gizmo
  87405. */
  87406. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87407. var _this = _super.call(this, gizmoLayer) || this;
  87408. // Create Material
  87409. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87410. coloredMaterial.disableLighting = true;
  87411. coloredMaterial.emissiveColor = color;
  87412. // Build mesh on root node
  87413. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87414. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87415. _this._rootMesh.addChild(arrowMesh);
  87416. _this._rootMesh.addChild(arrowTail);
  87417. // Position arrow pointing in its drag axis
  87418. arrowMesh.scaling.scaleInPlace(0.1);
  87419. arrowMesh.material = coloredMaterial;
  87420. arrowMesh.rotation.x = Math.PI / 2;
  87421. arrowMesh.position.z += 0.3;
  87422. arrowTail.rotation.x = Math.PI / 2;
  87423. arrowTail.material = coloredMaterial;
  87424. arrowTail.position.z += 0.2;
  87425. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87426. // Add drag behavior to handle events when the gizmo is dragged
  87427. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87428. _this._dragBehavior.moveAttached = false;
  87429. _this._rootMesh.addBehavior(_this._dragBehavior);
  87430. _this._dragBehavior.onDragObservable.add(function (event) {
  87431. if (!_this.interactionsEnabled) {
  87432. return;
  87433. }
  87434. if (_this.attachedMesh) {
  87435. _this.attachedMesh.scaling.addInPlace(event.delta);
  87436. }
  87437. });
  87438. return _this;
  87439. }
  87440. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87441. this._dragBehavior.enabled = value;
  87442. };
  87443. /**
  87444. * Disposes of the gizmo
  87445. */
  87446. AxisScaleGizmo.prototype.dispose = function () {
  87447. this._dragBehavior.detach();
  87448. _super.prototype.dispose.call(this);
  87449. };
  87450. return AxisScaleGizmo;
  87451. }(BABYLON.Gizmo));
  87452. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87453. })(BABYLON || (BABYLON = {}));
  87454. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87455. var BABYLON;
  87456. (function (BABYLON) {
  87457. /**
  87458. * Single plane rotation gizmo
  87459. */
  87460. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87461. __extends(PlaneRotationGizmo, _super);
  87462. /**
  87463. * Creates a PlaneRotationGizmo
  87464. * @param gizmoLayer The utility layer the gizmo will be added to
  87465. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87466. * @param color The color of the gizmo
  87467. */
  87468. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87469. var _this = _super.call(this, gizmoLayer) || this;
  87470. // Create Material
  87471. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87472. coloredMaterial.disableLighting = true;
  87473. coloredMaterial.emissiveColor = color;
  87474. // Build mesh on root node
  87475. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87476. _this._rootMesh.addChild(rotationMesh);
  87477. // Position arrow pointing in its drag axis
  87478. rotationMesh.scaling.scaleInPlace(0.1);
  87479. rotationMesh.material = coloredMaterial;
  87480. rotationMesh.rotation.x = Math.PI / 2;
  87481. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87482. // Add drag behavior to handle events when the gizmo is dragged
  87483. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87484. _this._dragBehavior.moveAttached = false;
  87485. _this._rootMesh.addBehavior(_this._dragBehavior);
  87486. var lastDragPosition = null;
  87487. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87488. if (!_this.interactionsEnabled) {
  87489. return;
  87490. }
  87491. lastDragPosition = e.dragPlanePoint;
  87492. });
  87493. _this._dragBehavior.onDragObservable.add(function (event) {
  87494. if (!_this.interactionsEnabled) {
  87495. return;
  87496. }
  87497. if (_this.attachedMesh && lastDragPosition) {
  87498. if (!_this.attachedMesh.rotationQuaternion) {
  87499. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87500. }
  87501. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87502. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87503. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87504. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87505. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87506. var angle = Math.atan2(cross.length(), dot);
  87507. var up = planeNormal.clone();
  87508. // Flip up vector depending on which side the camera is on
  87509. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87510. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87511. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87512. up.scaleInPlace(-1);
  87513. }
  87514. }
  87515. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87516. if (halfCircleSide)
  87517. angle = -angle;
  87518. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87519. var quaternionCoefficient = Math.sin(angle / 2);
  87520. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87521. // Rotate selected mesh quaternion over fixed axis
  87522. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87523. lastDragPosition = event.dragPlanePoint;
  87524. }
  87525. });
  87526. return _this;
  87527. }
  87528. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87529. this._dragBehavior.enabled = value;
  87530. };
  87531. /**
  87532. * Disposes of the gizmo
  87533. */
  87534. PlaneRotationGizmo.prototype.dispose = function () {
  87535. this._dragBehavior.detach();
  87536. _super.prototype.dispose.call(this);
  87537. };
  87538. return PlaneRotationGizmo;
  87539. }(BABYLON.Gizmo));
  87540. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87541. })(BABYLON || (BABYLON = {}));
  87542. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87543. var BABYLON;
  87544. (function (BABYLON) {
  87545. /**
  87546. * Gizmo that enables dragging a mesh along 3 axis
  87547. */
  87548. var PositionGizmo = /** @class */ (function (_super) {
  87549. __extends(PositionGizmo, _super);
  87550. /**
  87551. * Creates a PositionGizmo
  87552. * @param gizmoLayer The utility layer the gizmo will be added to
  87553. */
  87554. function PositionGizmo(gizmoLayer) {
  87555. var _this = _super.call(this, gizmoLayer) || this;
  87556. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87557. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87558. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87559. return _this;
  87560. }
  87561. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87562. set: function (mesh) {
  87563. this._xDrag.attachedMesh = mesh;
  87564. this._yDrag.attachedMesh = mesh;
  87565. this._zDrag.attachedMesh = mesh;
  87566. },
  87567. enumerable: true,
  87568. configurable: true
  87569. });
  87570. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87571. this._xDrag.interactionsEnabled = value;
  87572. this._yDrag.interactionsEnabled = value;
  87573. this._zDrag.interactionsEnabled = value;
  87574. };
  87575. /**
  87576. * Disposes of the gizmo
  87577. */
  87578. PositionGizmo.prototype.dispose = function () {
  87579. this._xDrag.dispose();
  87580. this._yDrag.dispose();
  87581. this._zDrag.dispose();
  87582. };
  87583. return PositionGizmo;
  87584. }(BABYLON.Gizmo));
  87585. BABYLON.PositionGizmo = PositionGizmo;
  87586. })(BABYLON || (BABYLON = {}));
  87587. //# sourceMappingURL=babylon.positionGizmo.js.map
  87588. var BABYLON;
  87589. (function (BABYLON) {
  87590. /**
  87591. * Gizmo that enables rotating a mesh along 3 axis
  87592. */
  87593. var RotationGizmo = /** @class */ (function (_super) {
  87594. __extends(RotationGizmo, _super);
  87595. /**
  87596. * Creates a RotationGizmo
  87597. * @param gizmoLayer The utility layer the gizmo will be added to
  87598. */
  87599. function RotationGizmo(gizmoLayer) {
  87600. var _this = _super.call(this, gizmoLayer) || this;
  87601. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87602. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87603. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87604. return _this;
  87605. }
  87606. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87607. set: function (mesh) {
  87608. this._xDrag.attachedMesh = mesh;
  87609. this._yDrag.attachedMesh = mesh;
  87610. this._zDrag.attachedMesh = mesh;
  87611. },
  87612. enumerable: true,
  87613. configurable: true
  87614. });
  87615. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87616. this._xDrag.interactionsEnabled = value;
  87617. this._yDrag.interactionsEnabled = value;
  87618. this._zDrag.interactionsEnabled = value;
  87619. };
  87620. /**
  87621. * Disposes of the gizmo
  87622. */
  87623. RotationGizmo.prototype.dispose = function () {
  87624. this._xDrag.dispose();
  87625. this._yDrag.dispose();
  87626. this._zDrag.dispose();
  87627. };
  87628. return RotationGizmo;
  87629. }(BABYLON.Gizmo));
  87630. BABYLON.RotationGizmo = RotationGizmo;
  87631. })(BABYLON || (BABYLON = {}));
  87632. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87633. var BABYLON;
  87634. (function (BABYLON) {
  87635. /**
  87636. * Gizmo that enables scaling a mesh along 3 axis
  87637. */
  87638. var ScaleGizmo = /** @class */ (function (_super) {
  87639. __extends(ScaleGizmo, _super);
  87640. /**
  87641. * Creates a ScaleGizmo
  87642. * @param gizmoLayer The utility layer the gizmo will be added to
  87643. */
  87644. function ScaleGizmo(gizmoLayer) {
  87645. var _this = _super.call(this, gizmoLayer) || this;
  87646. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87647. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87648. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87649. return _this;
  87650. }
  87651. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87652. set: function (mesh) {
  87653. this._xDrag.attachedMesh = mesh;
  87654. this._yDrag.attachedMesh = mesh;
  87655. this._zDrag.attachedMesh = mesh;
  87656. },
  87657. enumerable: true,
  87658. configurable: true
  87659. });
  87660. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87661. this._xDrag.interactionsEnabled = value;
  87662. this._yDrag.interactionsEnabled = value;
  87663. this._zDrag.interactionsEnabled = value;
  87664. };
  87665. /**
  87666. * Disposes of the gizmo
  87667. */
  87668. ScaleGizmo.prototype.dispose = function () {
  87669. this._xDrag.dispose();
  87670. this._yDrag.dispose();
  87671. this._zDrag.dispose();
  87672. };
  87673. return ScaleGizmo;
  87674. }(BABYLON.Gizmo));
  87675. BABYLON.ScaleGizmo = ScaleGizmo;
  87676. })(BABYLON || (BABYLON = {}));
  87677. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87678. var BABYLON;
  87679. (function (BABYLON) {
  87680. /**
  87681. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  87682. */
  87683. var GizmoManager = /** @class */ (function () {
  87684. /**
  87685. * Instatiates a gizmo manager
  87686. * @param scene the scene to overlay the gizmos on top of
  87687. * @param options If only a single gizmo should exist at one time
  87688. */
  87689. function GizmoManager(scene, options) {
  87690. var _this = this;
  87691. this.scene = scene;
  87692. // Set of gizmos that are currently in the scene for each mesh
  87693. this._gizmoSet = {};
  87694. this._pointerObserver = null;
  87695. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  87696. // Options parsing
  87697. if (!options) {
  87698. options = {};
  87699. }
  87700. if (options.singleGizmo === undefined) {
  87701. options.singleGizmo = true;
  87702. }
  87703. // Instatiate/dispose gizmos based on pointer actions
  87704. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  87705. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87706. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  87707. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  87708. if (options.singleGizmo) {
  87709. _this._clearGizmos();
  87710. }
  87711. // Enable gizmo when mesh is selected
  87712. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  87713. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87714. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87715. }
  87716. else {
  87717. if (!options.singleGizmo) {
  87718. // Disable gizmo when clicked again
  87719. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  87720. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  87721. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  87722. }
  87723. }
  87724. }
  87725. else {
  87726. if (options.singleGizmo) {
  87727. // Disable gizmo when clicked away
  87728. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87729. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  87730. if (gizmoPick && !gizmoPick.hit) {
  87731. _this._clearGizmos();
  87732. }
  87733. }
  87734. }
  87735. }
  87736. }
  87737. });
  87738. }
  87739. /**
  87740. * Disposes of the gizmo manager
  87741. */
  87742. GizmoManager.prototype.dispose = function () {
  87743. this.scene.onPointerObservable.remove(this._pointerObserver);
  87744. this._clearGizmos();
  87745. this._gizmoLayer.dispose();
  87746. };
  87747. GizmoManager.prototype._clearGizmos = function () {
  87748. for (var key in this._gizmoSet) {
  87749. if (this._gizmoSet.hasOwnProperty(key)) {
  87750. this._gizmoSet[key].positionGizmo.dispose();
  87751. this._gizmoSet[key].rotationGizmo.dispose();
  87752. delete this._gizmoSet[key];
  87753. }
  87754. }
  87755. };
  87756. return GizmoManager;
  87757. }());
  87758. BABYLON.GizmoManager = GizmoManager;
  87759. })(BABYLON || (BABYLON = {}));
  87760. //# sourceMappingURL=babylon.gizmoManager.js.map
  87761. var BABYLON;
  87762. (function (BABYLON) {
  87763. /**
  87764. * Defines a target to use with MorphTargetManager
  87765. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87766. */
  87767. var MorphTarget = /** @class */ (function () {
  87768. /**
  87769. * Creates a new MorphTarget
  87770. * @param name defines the name of the target
  87771. * @param influence defines the influence to use
  87772. */
  87773. function MorphTarget(
  87774. /** defines the name of the target */
  87775. name, influence, scene) {
  87776. if (influence === void 0) { influence = 0; }
  87777. if (scene === void 0) { scene = null; }
  87778. this.name = name;
  87779. /**
  87780. * Gets or sets the list of animations
  87781. */
  87782. this.animations = new Array();
  87783. this._positions = null;
  87784. this._normals = null;
  87785. this._tangents = null;
  87786. /**
  87787. * Observable raised when the influence changes
  87788. */
  87789. this.onInfluenceChanged = new BABYLON.Observable();
  87790. this._animationPropertiesOverride = null;
  87791. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87792. this.influence = influence;
  87793. }
  87794. Object.defineProperty(MorphTarget.prototype, "influence", {
  87795. /**
  87796. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  87797. */
  87798. get: function () {
  87799. return this._influence;
  87800. },
  87801. set: function (influence) {
  87802. if (this._influence === influence) {
  87803. return;
  87804. }
  87805. var previous = this._influence;
  87806. this._influence = influence;
  87807. if (this.onInfluenceChanged.hasObservers) {
  87808. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  87809. }
  87810. },
  87811. enumerable: true,
  87812. configurable: true
  87813. });
  87814. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  87815. /**
  87816. * Gets or sets the animation properties override
  87817. */
  87818. get: function () {
  87819. if (!this._animationPropertiesOverride && this._scene) {
  87820. return this._scene.animationPropertiesOverride;
  87821. }
  87822. return this._animationPropertiesOverride;
  87823. },
  87824. set: function (value) {
  87825. this._animationPropertiesOverride = value;
  87826. },
  87827. enumerable: true,
  87828. configurable: true
  87829. });
  87830. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  87831. /**
  87832. * Gets a boolean defining if the target contains position data
  87833. */
  87834. get: function () {
  87835. return !!this._positions;
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  87841. /**
  87842. * Gets a boolean defining if the target contains normal data
  87843. */
  87844. get: function () {
  87845. return !!this._normals;
  87846. },
  87847. enumerable: true,
  87848. configurable: true
  87849. });
  87850. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  87851. /**
  87852. * Gets a boolean defining if the target contains tangent data
  87853. */
  87854. get: function () {
  87855. return !!this._tangents;
  87856. },
  87857. enumerable: true,
  87858. configurable: true
  87859. });
  87860. /**
  87861. * Affects position data to this target
  87862. * @param data defines the position data to use
  87863. */
  87864. MorphTarget.prototype.setPositions = function (data) {
  87865. this._positions = data;
  87866. };
  87867. /**
  87868. * Gets the position data stored in this target
  87869. * @returns a FloatArray containing the position data (or null if not present)
  87870. */
  87871. MorphTarget.prototype.getPositions = function () {
  87872. return this._positions;
  87873. };
  87874. /**
  87875. * Affects normal data to this target
  87876. * @param data defines the normal data to use
  87877. */
  87878. MorphTarget.prototype.setNormals = function (data) {
  87879. this._normals = data;
  87880. };
  87881. /**
  87882. * Gets the normal data stored in this target
  87883. * @returns a FloatArray containing the normal data (or null if not present)
  87884. */
  87885. MorphTarget.prototype.getNormals = function () {
  87886. return this._normals;
  87887. };
  87888. /**
  87889. * Affects tangent data to this target
  87890. * @param data defines the tangent data to use
  87891. */
  87892. MorphTarget.prototype.setTangents = function (data) {
  87893. this._tangents = data;
  87894. };
  87895. /**
  87896. * Gets the tangent data stored in this target
  87897. * @returns a FloatArray containing the tangent data (or null if not present)
  87898. */
  87899. MorphTarget.prototype.getTangents = function () {
  87900. return this._tangents;
  87901. };
  87902. /**
  87903. * Serializes the current target into a Serialization object
  87904. * @returns the serialized object
  87905. */
  87906. MorphTarget.prototype.serialize = function () {
  87907. var serializationObject = {};
  87908. serializationObject.name = this.name;
  87909. serializationObject.influence = this.influence;
  87910. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  87911. if (this.hasNormals) {
  87912. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  87913. }
  87914. if (this.hasTangents) {
  87915. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  87916. }
  87917. // Animations
  87918. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  87919. return serializationObject;
  87920. };
  87921. // Statics
  87922. /**
  87923. * Creates a new target from serialized data
  87924. * @param serializationObject defines the serialized data to use
  87925. * @returns a new MorphTarget
  87926. */
  87927. MorphTarget.Parse = function (serializationObject) {
  87928. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  87929. result.setPositions(serializationObject.positions);
  87930. if (serializationObject.normals) {
  87931. result.setNormals(serializationObject.normals);
  87932. }
  87933. if (serializationObject.tangents) {
  87934. result.setTangents(serializationObject.tangents);
  87935. }
  87936. // Animations
  87937. if (serializationObject.animations) {
  87938. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  87939. var parsedAnimation = serializationObject.animations[animationIndex];
  87940. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  87941. }
  87942. }
  87943. return result;
  87944. };
  87945. /**
  87946. * Creates a MorphTarget from mesh data
  87947. * @param mesh defines the source mesh
  87948. * @param name defines the name to use for the new target
  87949. * @param influence defines the influence to attach to the target
  87950. * @returns a new MorphTarget
  87951. */
  87952. MorphTarget.FromMesh = function (mesh, name, influence) {
  87953. if (!name) {
  87954. name = mesh.name;
  87955. }
  87956. var result = new MorphTarget(name, influence, mesh.getScene());
  87957. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87959. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  87960. }
  87961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  87962. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  87963. }
  87964. return result;
  87965. };
  87966. return MorphTarget;
  87967. }());
  87968. BABYLON.MorphTarget = MorphTarget;
  87969. })(BABYLON || (BABYLON = {}));
  87970. //# sourceMappingURL=babylon.morphTarget.js.map
  87971. var BABYLON;
  87972. (function (BABYLON) {
  87973. /**
  87974. * This class is used to deform meshes using morphing between different targets
  87975. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87976. */
  87977. var MorphTargetManager = /** @class */ (function () {
  87978. /**
  87979. * Creates a new MorphTargetManager
  87980. * @param scene defines the current scene
  87981. */
  87982. function MorphTargetManager(scene) {
  87983. if (scene === void 0) { scene = null; }
  87984. this._targets = new Array();
  87985. this._targetObservable = new Array();
  87986. this._activeTargets = new BABYLON.SmartArray(16);
  87987. this._supportsNormals = false;
  87988. this._supportsTangents = false;
  87989. this._vertexCount = 0;
  87990. this._uniqueId = 0;
  87991. this._tempInfluences = new Array();
  87992. if (!scene) {
  87993. scene = BABYLON.Engine.LastCreatedScene;
  87994. }
  87995. this._scene = scene;
  87996. if (this._scene) {
  87997. this._scene.morphTargetManagers.push(this);
  87998. this._uniqueId = this._scene.getUniqueId();
  87999. }
  88000. }
  88001. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88002. /**
  88003. * Gets the unique ID of this manager
  88004. */
  88005. get: function () {
  88006. return this._uniqueId;
  88007. },
  88008. enumerable: true,
  88009. configurable: true
  88010. });
  88011. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88012. /**
  88013. * Gets the number of vertices handled by this manager
  88014. */
  88015. get: function () {
  88016. return this._vertexCount;
  88017. },
  88018. enumerable: true,
  88019. configurable: true
  88020. });
  88021. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88022. /**
  88023. * Gets a boolean indicating if this manager supports morphing of normals
  88024. */
  88025. get: function () {
  88026. return this._supportsNormals;
  88027. },
  88028. enumerable: true,
  88029. configurable: true
  88030. });
  88031. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88032. /**
  88033. * Gets a boolean indicating if this manager supports morphing of tangents
  88034. */
  88035. get: function () {
  88036. return this._supportsTangents;
  88037. },
  88038. enumerable: true,
  88039. configurable: true
  88040. });
  88041. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88042. /**
  88043. * Gets the number of targets stored in this manager
  88044. */
  88045. get: function () {
  88046. return this._targets.length;
  88047. },
  88048. enumerable: true,
  88049. configurable: true
  88050. });
  88051. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88052. /**
  88053. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88054. */
  88055. get: function () {
  88056. return this._activeTargets.length;
  88057. },
  88058. enumerable: true,
  88059. configurable: true
  88060. });
  88061. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88062. /**
  88063. * Gets the list of influences (one per target)
  88064. */
  88065. get: function () {
  88066. return this._influences;
  88067. },
  88068. enumerable: true,
  88069. configurable: true
  88070. });
  88071. /**
  88072. * Gets the active target at specified index. An active target is a target with an influence > 0
  88073. * @param index defines the index to check
  88074. * @returns the requested target
  88075. */
  88076. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88077. return this._activeTargets.data[index];
  88078. };
  88079. /**
  88080. * Gets the target at specified index
  88081. * @param index defines the index to check
  88082. * @returns the requested target
  88083. */
  88084. MorphTargetManager.prototype.getTarget = function (index) {
  88085. return this._targets[index];
  88086. };
  88087. /**
  88088. * Add a new target to this manager
  88089. * @param target defines the target to add
  88090. */
  88091. MorphTargetManager.prototype.addTarget = function (target) {
  88092. var _this = this;
  88093. this._targets.push(target);
  88094. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88095. _this._syncActiveTargets(needUpdate);
  88096. }));
  88097. this._syncActiveTargets(true);
  88098. };
  88099. /**
  88100. * Removes a target from the manager
  88101. * @param target defines the target to remove
  88102. */
  88103. MorphTargetManager.prototype.removeTarget = function (target) {
  88104. var index = this._targets.indexOf(target);
  88105. if (index >= 0) {
  88106. this._targets.splice(index, 1);
  88107. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88108. this._syncActiveTargets(true);
  88109. }
  88110. };
  88111. /**
  88112. * Serializes the current manager into a Serialization object
  88113. * @returns the serialized object
  88114. */
  88115. MorphTargetManager.prototype.serialize = function () {
  88116. var serializationObject = {};
  88117. serializationObject.id = this.uniqueId;
  88118. serializationObject.targets = [];
  88119. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88120. var target = _a[_i];
  88121. serializationObject.targets.push(target.serialize());
  88122. }
  88123. return serializationObject;
  88124. };
  88125. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88126. var influenceCount = 0;
  88127. this._activeTargets.reset();
  88128. this._supportsNormals = true;
  88129. this._supportsTangents = true;
  88130. this._vertexCount = 0;
  88131. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88132. var target = _a[_i];
  88133. this._activeTargets.push(target);
  88134. this._tempInfluences[influenceCount++] = target.influence;
  88135. var positions = target.getPositions();
  88136. if (positions) {
  88137. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88138. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88139. var vertexCount = positions.length / 3;
  88140. if (this._vertexCount === 0) {
  88141. this._vertexCount = vertexCount;
  88142. }
  88143. else if (this._vertexCount !== vertexCount) {
  88144. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88145. return;
  88146. }
  88147. }
  88148. }
  88149. if (!this._influences || this._influences.length !== influenceCount) {
  88150. this._influences = new Float32Array(influenceCount);
  88151. }
  88152. for (var index = 0; index < influenceCount; index++) {
  88153. this._influences[index] = this._tempInfluences[index];
  88154. }
  88155. if (needUpdate) {
  88156. this.synchronize();
  88157. }
  88158. };
  88159. /**
  88160. * Syncrhonize the targets with all the meshes using this morph target manager
  88161. */
  88162. MorphTargetManager.prototype.synchronize = function () {
  88163. if (!this._scene) {
  88164. return;
  88165. }
  88166. // Flag meshes as dirty to resync with the active targets
  88167. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88168. var mesh = _a[_i];
  88169. if (mesh.morphTargetManager === this) {
  88170. mesh._syncGeometryWithMorphTargetManager();
  88171. }
  88172. }
  88173. };
  88174. // Statics
  88175. /**
  88176. * Creates a new MorphTargetManager from serialized data
  88177. * @param serializationObject defines the serialized data
  88178. * @param scene defines the hosting scene
  88179. * @returns the new MorphTargetManager
  88180. */
  88181. MorphTargetManager.Parse = function (serializationObject, scene) {
  88182. var result = new MorphTargetManager(scene);
  88183. result._uniqueId = serializationObject.id;
  88184. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88185. var targetData = _a[_i];
  88186. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88187. }
  88188. return result;
  88189. };
  88190. return MorphTargetManager;
  88191. }());
  88192. BABYLON.MorphTargetManager = MorphTargetManager;
  88193. })(BABYLON || (BABYLON = {}));
  88194. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88195. var BABYLON;
  88196. (function (BABYLON) {
  88197. var Octree = /** @class */ (function () {
  88198. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88199. if (maxDepth === void 0) { maxDepth = 2; }
  88200. this.maxDepth = maxDepth;
  88201. this.dynamicContent = new Array();
  88202. this._maxBlockCapacity = maxBlockCapacity || 64;
  88203. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88204. this._creationFunc = creationFunc;
  88205. }
  88206. // Methods
  88207. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88208. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88209. };
  88210. Octree.prototype.addMesh = function (entry) {
  88211. for (var index = 0; index < this.blocks.length; index++) {
  88212. var block = this.blocks[index];
  88213. block.addEntry(entry);
  88214. }
  88215. };
  88216. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88217. this._selectionContent.reset();
  88218. for (var index = 0; index < this.blocks.length; index++) {
  88219. var block = this.blocks[index];
  88220. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88221. }
  88222. if (allowDuplicate) {
  88223. this._selectionContent.concat(this.dynamicContent);
  88224. }
  88225. else {
  88226. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88227. }
  88228. return this._selectionContent;
  88229. };
  88230. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88231. this._selectionContent.reset();
  88232. for (var index = 0; index < this.blocks.length; index++) {
  88233. var block = this.blocks[index];
  88234. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88235. }
  88236. if (allowDuplicate) {
  88237. this._selectionContent.concat(this.dynamicContent);
  88238. }
  88239. else {
  88240. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88241. }
  88242. return this._selectionContent;
  88243. };
  88244. Octree.prototype.intersectsRay = function (ray) {
  88245. this._selectionContent.reset();
  88246. for (var index = 0; index < this.blocks.length; index++) {
  88247. var block = this.blocks[index];
  88248. block.intersectsRay(ray, this._selectionContent);
  88249. }
  88250. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88251. return this._selectionContent;
  88252. };
  88253. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88254. target.blocks = new Array();
  88255. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88256. // Segmenting space
  88257. for (var x = 0; x < 2; x++) {
  88258. for (var y = 0; y < 2; y++) {
  88259. for (var z = 0; z < 2; z++) {
  88260. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88261. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88262. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88263. block.addEntries(entries);
  88264. target.blocks.push(block);
  88265. }
  88266. }
  88267. }
  88268. };
  88269. Octree.CreationFuncForMeshes = function (entry, block) {
  88270. var boundingInfo = entry.getBoundingInfo();
  88271. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88272. block.entries.push(entry);
  88273. }
  88274. };
  88275. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88276. var boundingInfo = entry.getBoundingInfo();
  88277. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88278. block.entries.push(entry);
  88279. }
  88280. };
  88281. return Octree;
  88282. }());
  88283. BABYLON.Octree = Octree;
  88284. })(BABYLON || (BABYLON = {}));
  88285. //# sourceMappingURL=babylon.octree.js.map
  88286. var BABYLON;
  88287. (function (BABYLON) {
  88288. var OctreeBlock = /** @class */ (function () {
  88289. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88290. this.entries = new Array();
  88291. this._boundingVectors = new Array();
  88292. this._capacity = capacity;
  88293. this._depth = depth;
  88294. this._maxDepth = maxDepth;
  88295. this._creationFunc = creationFunc;
  88296. this._minPoint = minPoint;
  88297. this._maxPoint = maxPoint;
  88298. this._boundingVectors.push(minPoint.clone());
  88299. this._boundingVectors.push(maxPoint.clone());
  88300. this._boundingVectors.push(minPoint.clone());
  88301. this._boundingVectors[2].x = maxPoint.x;
  88302. this._boundingVectors.push(minPoint.clone());
  88303. this._boundingVectors[3].y = maxPoint.y;
  88304. this._boundingVectors.push(minPoint.clone());
  88305. this._boundingVectors[4].z = maxPoint.z;
  88306. this._boundingVectors.push(maxPoint.clone());
  88307. this._boundingVectors[5].z = minPoint.z;
  88308. this._boundingVectors.push(maxPoint.clone());
  88309. this._boundingVectors[6].x = minPoint.x;
  88310. this._boundingVectors.push(maxPoint.clone());
  88311. this._boundingVectors[7].y = minPoint.y;
  88312. }
  88313. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88314. // Property
  88315. get: function () {
  88316. return this._capacity;
  88317. },
  88318. enumerable: true,
  88319. configurable: true
  88320. });
  88321. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88322. get: function () {
  88323. return this._minPoint;
  88324. },
  88325. enumerable: true,
  88326. configurable: true
  88327. });
  88328. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88329. get: function () {
  88330. return this._maxPoint;
  88331. },
  88332. enumerable: true,
  88333. configurable: true
  88334. });
  88335. // Methods
  88336. OctreeBlock.prototype.addEntry = function (entry) {
  88337. if (this.blocks) {
  88338. for (var index = 0; index < this.blocks.length; index++) {
  88339. var block = this.blocks[index];
  88340. block.addEntry(entry);
  88341. }
  88342. return;
  88343. }
  88344. this._creationFunc(entry, this);
  88345. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88346. this.createInnerBlocks();
  88347. }
  88348. };
  88349. OctreeBlock.prototype.addEntries = function (entries) {
  88350. for (var index = 0; index < entries.length; index++) {
  88351. var mesh = entries[index];
  88352. this.addEntry(mesh);
  88353. }
  88354. };
  88355. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88356. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88357. if (this.blocks) {
  88358. for (var index = 0; index < this.blocks.length; index++) {
  88359. var block = this.blocks[index];
  88360. block.select(frustumPlanes, selection, allowDuplicate);
  88361. }
  88362. return;
  88363. }
  88364. if (allowDuplicate) {
  88365. selection.concat(this.entries);
  88366. }
  88367. else {
  88368. selection.concatWithNoDuplicate(this.entries);
  88369. }
  88370. }
  88371. };
  88372. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88373. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88374. if (this.blocks) {
  88375. for (var index = 0; index < this.blocks.length; index++) {
  88376. var block = this.blocks[index];
  88377. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88378. }
  88379. return;
  88380. }
  88381. if (allowDuplicate) {
  88382. selection.concat(this.entries);
  88383. }
  88384. else {
  88385. selection.concatWithNoDuplicate(this.entries);
  88386. }
  88387. }
  88388. };
  88389. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88390. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88391. if (this.blocks) {
  88392. for (var index = 0; index < this.blocks.length; index++) {
  88393. var block = this.blocks[index];
  88394. block.intersectsRay(ray, selection);
  88395. }
  88396. return;
  88397. }
  88398. selection.concatWithNoDuplicate(this.entries);
  88399. }
  88400. };
  88401. OctreeBlock.prototype.createInnerBlocks = function () {
  88402. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88403. };
  88404. return OctreeBlock;
  88405. }());
  88406. BABYLON.OctreeBlock = OctreeBlock;
  88407. })(BABYLON || (BABYLON = {}));
  88408. //# sourceMappingURL=babylon.octreeBlock.js.map
  88409. var BABYLON;
  88410. (function (BABYLON) {
  88411. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88412. __extends(VRDistortionCorrectionPostProcess, _super);
  88413. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88414. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88415. 'LensCenter',
  88416. 'Scale',
  88417. 'ScaleIn',
  88418. 'HmdWarpParam'
  88419. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88420. _this._isRightEye = isRightEye;
  88421. _this._distortionFactors = vrMetrics.distortionK;
  88422. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88423. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88424. _this.adaptScaleToCurrentViewport = true;
  88425. _this.onSizeChangedObservable.add(function () {
  88426. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88427. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88428. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88429. });
  88430. _this.onApplyObservable.add(function (effect) {
  88431. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88432. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88433. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88434. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88435. });
  88436. return _this;
  88437. }
  88438. return VRDistortionCorrectionPostProcess;
  88439. }(BABYLON.PostProcess));
  88440. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88441. })(BABYLON || (BABYLON = {}));
  88442. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88443. var BABYLON;
  88444. (function (BABYLON) {
  88445. /**
  88446. * Postprocess used to generate anaglyphic rendering
  88447. */
  88448. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88449. __extends(AnaglyphPostProcess, _super);
  88450. /**
  88451. * Creates a new AnaglyphPostProcess
  88452. * @param name defines postprocess name
  88453. * @param options defines creation options or target ratio scale
  88454. * @param rigCameras defines cameras using this postprocess
  88455. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88456. * @param engine defines hosting engine
  88457. * @param reusable defines if the postprocess will be reused multiple times per frame
  88458. */
  88459. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88460. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88461. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88462. _this.onApplyObservable.add(function (effect) {
  88463. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88464. });
  88465. return _this;
  88466. }
  88467. return AnaglyphPostProcess;
  88468. }(BABYLON.PostProcess));
  88469. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88470. })(BABYLON || (BABYLON = {}));
  88471. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88472. var BABYLON;
  88473. (function (BABYLON) {
  88474. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88475. __extends(StereoscopicInterlacePostProcess, _super);
  88476. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88477. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88478. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88479. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88480. _this.onSizeChangedObservable.add(function () {
  88481. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88482. });
  88483. _this.onApplyObservable.add(function (effect) {
  88484. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88485. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88486. });
  88487. return _this;
  88488. }
  88489. return StereoscopicInterlacePostProcess;
  88490. }(BABYLON.PostProcess));
  88491. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88492. })(BABYLON || (BABYLON = {}));
  88493. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88494. var BABYLON;
  88495. (function (BABYLON) {
  88496. /**
  88497. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88498. * Screen rotation is taken into account.
  88499. */
  88500. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88501. function FreeCameraDeviceOrientationInput() {
  88502. var _this = this;
  88503. this._screenOrientationAngle = 0;
  88504. this._screenQuaternion = new BABYLON.Quaternion();
  88505. this._alpha = 0;
  88506. this._beta = 0;
  88507. this._gamma = 0;
  88508. this._orientationChanged = function () {
  88509. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88510. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88511. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88512. };
  88513. this._deviceOrientation = function (evt) {
  88514. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88515. _this._beta = evt.beta !== null ? evt.beta : 0;
  88516. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88517. };
  88518. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88519. this._orientationChanged();
  88520. }
  88521. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88522. get: function () {
  88523. return this._camera;
  88524. },
  88525. set: function (camera) {
  88526. this._camera = camera;
  88527. if (this._camera != null && !this._camera.rotationQuaternion) {
  88528. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88529. }
  88530. },
  88531. enumerable: true,
  88532. configurable: true
  88533. });
  88534. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88535. window.addEventListener("orientationchange", this._orientationChanged);
  88536. window.addEventListener("deviceorientation", this._deviceOrientation);
  88537. //In certain cases, the attach control is called AFTER orientation was changed,
  88538. //So this is needed.
  88539. this._orientationChanged();
  88540. };
  88541. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88542. window.removeEventListener("orientationchange", this._orientationChanged);
  88543. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88544. };
  88545. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88546. //if no device orientation provided, don't update the rotation.
  88547. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88548. if (!this._alpha)
  88549. return;
  88550. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88551. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88552. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88553. //Mirror on XY Plane
  88554. this._camera.rotationQuaternion.z *= -1;
  88555. this._camera.rotationQuaternion.w *= -1;
  88556. };
  88557. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88558. return "FreeCameraDeviceOrientationInput";
  88559. };
  88560. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88561. return "deviceOrientation";
  88562. };
  88563. return FreeCameraDeviceOrientationInput;
  88564. }());
  88565. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88566. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88567. })(BABYLON || (BABYLON = {}));
  88568. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88569. var BABYLON;
  88570. (function (BABYLON) {
  88571. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88572. function ArcRotateCameraVRDeviceOrientationInput() {
  88573. this.alphaCorrection = 1;
  88574. this.betaCorrection = 1;
  88575. this.gammaCorrection = 1;
  88576. this._alpha = 0;
  88577. this._gamma = 0;
  88578. this._dirty = false;
  88579. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88580. }
  88581. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88582. this.camera.attachControl(element, noPreventDefault);
  88583. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88584. };
  88585. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88586. if (evt.alpha !== null) {
  88587. this._alpha = +evt.alpha | 0;
  88588. }
  88589. if (evt.gamma !== null) {
  88590. this._gamma = +evt.gamma | 0;
  88591. }
  88592. this._dirty = true;
  88593. };
  88594. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88595. if (this._dirty) {
  88596. this._dirty = false;
  88597. if (this._gamma < 0) {
  88598. this._gamma = 180 + this._gamma;
  88599. }
  88600. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88601. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88602. }
  88603. };
  88604. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88605. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88606. };
  88607. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88608. return "ArcRotateCameraVRDeviceOrientationInput";
  88609. };
  88610. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88611. return "VRDeviceOrientation";
  88612. };
  88613. return ArcRotateCameraVRDeviceOrientationInput;
  88614. }());
  88615. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  88616. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  88617. })(BABYLON || (BABYLON = {}));
  88618. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  88619. var BABYLON;
  88620. (function (BABYLON) {
  88621. var VRCameraMetrics = /** @class */ (function () {
  88622. function VRCameraMetrics() {
  88623. this.compensateDistortion = true;
  88624. }
  88625. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  88626. get: function () {
  88627. return this.hResolution / (2 * this.vResolution);
  88628. },
  88629. enumerable: true,
  88630. configurable: true
  88631. });
  88632. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  88633. get: function () {
  88634. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  88635. },
  88636. enumerable: true,
  88637. configurable: true
  88638. });
  88639. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  88640. get: function () {
  88641. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88642. var h = (4 * meters) / this.hScreenSize;
  88643. return BABYLON.Matrix.Translation(h, 0, 0);
  88644. },
  88645. enumerable: true,
  88646. configurable: true
  88647. });
  88648. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  88649. get: function () {
  88650. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88651. var h = (4 * meters) / this.hScreenSize;
  88652. return BABYLON.Matrix.Translation(-h, 0, 0);
  88653. },
  88654. enumerable: true,
  88655. configurable: true
  88656. });
  88657. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  88658. get: function () {
  88659. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  88660. },
  88661. enumerable: true,
  88662. configurable: true
  88663. });
  88664. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  88665. get: function () {
  88666. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  88667. },
  88668. enumerable: true,
  88669. configurable: true
  88670. });
  88671. VRCameraMetrics.GetDefault = function () {
  88672. var result = new VRCameraMetrics();
  88673. result.hResolution = 1280;
  88674. result.vResolution = 800;
  88675. result.hScreenSize = 0.149759993;
  88676. result.vScreenSize = 0.0935999975;
  88677. result.vScreenCenter = 0.0467999987;
  88678. result.eyeToScreenDistance = 0.0410000011;
  88679. result.lensSeparationDistance = 0.0635000020;
  88680. result.interpupillaryDistance = 0.0640000030;
  88681. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  88682. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  88683. result.postProcessScaleFactor = 1.714605507808412;
  88684. result.lensCenterOffset = 0.151976421;
  88685. return result;
  88686. };
  88687. return VRCameraMetrics;
  88688. }());
  88689. BABYLON.VRCameraMetrics = VRCameraMetrics;
  88690. })(BABYLON || (BABYLON = {}));
  88691. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  88692. var BABYLON;
  88693. (function (BABYLON) {
  88694. /**
  88695. * This represents a WebVR camera.
  88696. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  88697. * @example http://doc.babylonjs.com/how_to/webvr_camera
  88698. */
  88699. var WebVRFreeCamera = /** @class */ (function (_super) {
  88700. __extends(WebVRFreeCamera, _super);
  88701. /**
  88702. * Instantiates a WebVRFreeCamera.
  88703. * @param name The name of the WebVRFreeCamera
  88704. * @param position The starting anchor position for the camera
  88705. * @param scene The scene the camera belongs to
  88706. * @param webVROptions a set of customizable options for the webVRCamera
  88707. */
  88708. function WebVRFreeCamera(name, position, scene, webVROptions) {
  88709. if (webVROptions === void 0) { webVROptions = {}; }
  88710. var _this = _super.call(this, name, position, scene) || this;
  88711. _this.webVROptions = webVROptions;
  88712. /**
  88713. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  88714. */
  88715. _this._vrDevice = null;
  88716. /**
  88717. * The rawPose of the vrDevice.
  88718. */
  88719. _this.rawPose = null;
  88720. _this._specsVersion = "1.1";
  88721. _this._attached = false;
  88722. _this._descendants = [];
  88723. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  88724. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  88725. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  88726. _this._standingMatrix = null;
  88727. /**
  88728. * Represents device position in babylon space.
  88729. */
  88730. _this.devicePosition = BABYLON.Vector3.Zero();
  88731. /**
  88732. * Represents device rotation in babylon space.
  88733. */
  88734. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  88735. /**
  88736. * The scale of the device to be used when translating from device space to babylon space.
  88737. */
  88738. _this.deviceScaleFactor = 1;
  88739. _this._deviceToWorld = BABYLON.Matrix.Identity();
  88740. _this._worldToDevice = BABYLON.Matrix.Identity();
  88741. /**
  88742. * References to the webVR controllers for the vrDevice.
  88743. */
  88744. _this.controllers = [];
  88745. /**
  88746. * Emits an event when a controller is attached.
  88747. */
  88748. _this.onControllersAttachedObservable = new BABYLON.Observable();
  88749. /**
  88750. * Emits an event when a controller's mesh has been loaded;
  88751. */
  88752. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88753. /**
  88754. * If the rig cameras be used as parent instead of this camera.
  88755. */
  88756. _this.rigParenting = true;
  88757. _this._defaultHeight = undefined;
  88758. _this._workingVector = BABYLON.Vector3.Zero();
  88759. _this._oneVector = BABYLON.Vector3.One();
  88760. _this._workingMatrix = BABYLON.Matrix.Identity();
  88761. _this._cache.position = BABYLON.Vector3.Zero();
  88762. if (webVROptions.defaultHeight) {
  88763. _this._defaultHeight = webVROptions.defaultHeight;
  88764. _this.position.y = _this._defaultHeight;
  88765. }
  88766. _this.minZ = 0.1;
  88767. //legacy support - the compensation boolean was removed.
  88768. if (arguments.length === 5) {
  88769. _this.webVROptions = arguments[4];
  88770. }
  88771. // default webVR options
  88772. if (_this.webVROptions.trackPosition == undefined) {
  88773. _this.webVROptions.trackPosition = true;
  88774. }
  88775. if (_this.webVROptions.controllerMeshes == undefined) {
  88776. _this.webVROptions.controllerMeshes = true;
  88777. }
  88778. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  88779. _this.webVROptions.defaultLightingOnControllers = true;
  88780. }
  88781. _this.rotationQuaternion = new BABYLON.Quaternion();
  88782. if (_this.webVROptions && _this.webVROptions.positionScale) {
  88783. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  88784. }
  88785. //enable VR
  88786. var engine = _this.getEngine();
  88787. _this._onVREnabled = function (success) { if (success) {
  88788. _this.initControllers();
  88789. } };
  88790. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  88791. engine.initWebVR().add(function (event) {
  88792. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  88793. return;
  88794. }
  88795. _this._vrDevice = event.vrDisplay;
  88796. //reset the rig parameters.
  88797. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  88798. if (_this._attached) {
  88799. _this.getEngine().enableVR();
  88800. }
  88801. });
  88802. if (typeof (VRFrameData) !== "undefined")
  88803. _this._frameData = new VRFrameData();
  88804. /**
  88805. * The idea behind the following lines:
  88806. * objects that have the camera as parent should actually have the rig cameras as a parent.
  88807. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  88808. * the second will not show it correctly.
  88809. *
  88810. * To solve this - each object that has the camera as parent will be added to a protected array.
  88811. * When the rig camera renders, it will take this array and set all of those to be its children.
  88812. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  88813. * Amazing!
  88814. */
  88815. scene.onBeforeCameraRenderObservable.add(function (camera) {
  88816. if (camera.parent === _this && _this.rigParenting) {
  88817. _this._descendants = _this.getDescendants(true, function (n) {
  88818. // don't take the cameras or the controllers!
  88819. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  88820. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  88821. return !isController && !isRigCamera;
  88822. });
  88823. _this._descendants.forEach(function (node) {
  88824. node.parent = camera;
  88825. });
  88826. }
  88827. });
  88828. scene.onAfterCameraRenderObservable.add(function (camera) {
  88829. if (camera.parent === _this && _this.rigParenting) {
  88830. _this._descendants.forEach(function (node) {
  88831. node.parent = _this;
  88832. });
  88833. }
  88834. });
  88835. return _this;
  88836. }
  88837. /**
  88838. * Gets the device distance from the ground in meters.
  88839. * @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.
  88840. */
  88841. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  88842. if (this._standingMatrix) {
  88843. // Add standing matrix offset to get real offset from ground in room
  88844. this._standingMatrix.getTranslationToRef(this._workingVector);
  88845. return this._deviceRoomPosition.y + this._workingVector.y;
  88846. }
  88847. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  88848. return this._defaultHeight || 0;
  88849. };
  88850. /**
  88851. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88852. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  88853. */
  88854. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  88855. var _this = this;
  88856. if (callback === void 0) { callback = function (bool) { }; }
  88857. // Use standing matrix if available
  88858. this.getEngine().initWebVRAsync().then(function (result) {
  88859. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  88860. callback(false);
  88861. }
  88862. else {
  88863. _this._standingMatrix = new BABYLON.Matrix();
  88864. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  88865. if (!_this.getScene().useRightHandedSystem) {
  88866. [2, 6, 8, 9, 14].forEach(function (num) {
  88867. if (_this._standingMatrix) {
  88868. _this._standingMatrix.m[num] *= -1;
  88869. }
  88870. });
  88871. }
  88872. callback(true);
  88873. }
  88874. });
  88875. };
  88876. /**
  88877. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88878. * @returns A promise with a boolean set to if the standing matrix is supported.
  88879. */
  88880. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  88881. var _this = this;
  88882. return new Promise(function (res, rej) {
  88883. _this.useStandingMatrix(function (supported) {
  88884. res(supported);
  88885. });
  88886. });
  88887. };
  88888. /**
  88889. * Disposes the camera
  88890. */
  88891. WebVRFreeCamera.prototype.dispose = function () {
  88892. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  88893. _super.prototype.dispose.call(this);
  88894. };
  88895. /**
  88896. * Gets a vrController by name.
  88897. * @param name The name of the controller to retreive
  88898. * @returns the controller matching the name specified or null if not found
  88899. */
  88900. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  88901. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  88902. var gp = _a[_i];
  88903. if (gp.hand === name) {
  88904. return gp;
  88905. }
  88906. }
  88907. return null;
  88908. };
  88909. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  88910. /**
  88911. * The controller corrisponding to the users left hand.
  88912. */
  88913. get: function () {
  88914. if (!this._leftController) {
  88915. this._leftController = this.getControllerByName("left");
  88916. }
  88917. return this._leftController;
  88918. },
  88919. enumerable: true,
  88920. configurable: true
  88921. });
  88922. ;
  88923. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  88924. /**
  88925. * The controller corrisponding to the users right hand.
  88926. */
  88927. get: function () {
  88928. if (!this._rightController) {
  88929. this._rightController = this.getControllerByName("right");
  88930. }
  88931. return this._rightController;
  88932. },
  88933. enumerable: true,
  88934. configurable: true
  88935. });
  88936. ;
  88937. /**
  88938. * Casts a ray forward from the vrCamera's gaze.
  88939. * @param length Length of the ray (default: 100)
  88940. * @returns the ray corrisponding to the gaze
  88941. */
  88942. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  88943. if (length === void 0) { length = 100; }
  88944. if (this.leftCamera) {
  88945. // Use left eye to avoid computation to compute center on every call
  88946. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  88947. }
  88948. else {
  88949. return _super.prototype.getForwardRay.call(this, length);
  88950. }
  88951. };
  88952. /**
  88953. * Updates the camera based on device's frame data
  88954. */
  88955. WebVRFreeCamera.prototype._checkInputs = function () {
  88956. if (this._vrDevice && this._vrDevice.isPresenting) {
  88957. this._vrDevice.getFrameData(this._frameData);
  88958. this.updateFromDevice(this._frameData.pose);
  88959. }
  88960. _super.prototype._checkInputs.call(this);
  88961. };
  88962. /**
  88963. * Updates the poseControlled values based on the input device pose.
  88964. * @param poseData Pose coming from the device
  88965. */
  88966. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  88967. if (poseData && poseData.orientation) {
  88968. this.rawPose = poseData;
  88969. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  88970. if (this.getScene().useRightHandedSystem) {
  88971. this._deviceRoomRotationQuaternion.z *= -1;
  88972. this._deviceRoomRotationQuaternion.w *= -1;
  88973. }
  88974. if (this.webVROptions.trackPosition && this.rawPose.position) {
  88975. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  88976. if (this.getScene().useRightHandedSystem) {
  88977. this._deviceRoomPosition.z *= -1;
  88978. }
  88979. }
  88980. }
  88981. };
  88982. /**
  88983. * WebVR's attach control will start broadcasting frames to the device.
  88984. * Note that in certain browsers (chrome for example) this function must be called
  88985. * within a user-interaction callback. Example:
  88986. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  88987. *
  88988. * @param element html element to attach the vrDevice to
  88989. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  88990. */
  88991. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  88992. _super.prototype.attachControl.call(this, element, noPreventDefault);
  88993. this._attached = true;
  88994. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  88995. if (this._vrDevice) {
  88996. this.getEngine().enableVR();
  88997. }
  88998. };
  88999. /**
  89000. * Detaches the camera from the html element and disables VR
  89001. *
  89002. * @param element html element to detach from
  89003. */
  89004. WebVRFreeCamera.prototype.detachControl = function (element) {
  89005. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89006. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89007. _super.prototype.detachControl.call(this, element);
  89008. this._attached = false;
  89009. this.getEngine().disableVR();
  89010. };
  89011. /**
  89012. * @returns the name of this class
  89013. */
  89014. WebVRFreeCamera.prototype.getClassName = function () {
  89015. return "WebVRFreeCamera";
  89016. };
  89017. /**
  89018. * Calls resetPose on the vrDisplay
  89019. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89020. */
  89021. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89022. //uses the vrDisplay's "resetPose()".
  89023. //pitch and roll won't be affected.
  89024. this._vrDevice.resetPose();
  89025. };
  89026. /**
  89027. * Updates the rig cameras (left and right eye)
  89028. */
  89029. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89030. var camLeft = this._rigCameras[0];
  89031. var camRight = this._rigCameras[1];
  89032. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89033. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89034. camLeft.position.copyFrom(this._deviceRoomPosition);
  89035. camRight.position.copyFrom(this._deviceRoomPosition);
  89036. };
  89037. /**
  89038. * Updates the cached values of the camera
  89039. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89040. */
  89041. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89042. var _this = this;
  89043. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89044. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89045. if (!this.updateCacheCalled) {
  89046. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89047. this.updateCacheCalled = true;
  89048. this.update();
  89049. }
  89050. // Set working vector to the device position in room space rotated by the new rotation
  89051. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89052. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89053. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89054. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89055. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89056. // Add translation from anchor position
  89057. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89058. this._workingVector.addInPlace(this.position);
  89059. this._workingVector.subtractInPlace(this._cache.position);
  89060. this._deviceToWorld.setTranslation(this._workingVector);
  89061. // Set an inverted matrix to be used when updating the camera
  89062. this._deviceToWorld.invertToRef(this._worldToDevice);
  89063. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89064. this.controllers.forEach(function (controller) {
  89065. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89066. controller.update();
  89067. });
  89068. }
  89069. if (!ignoreParentClass) {
  89070. _super.prototype._updateCache.call(this);
  89071. }
  89072. this.updateCacheCalled = false;
  89073. };
  89074. /**
  89075. * Updates the current device position and rotation in the babylon world
  89076. */
  89077. WebVRFreeCamera.prototype.update = function () {
  89078. // Get current device position in babylon world
  89079. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89080. // Get current device rotation in babylon world
  89081. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89082. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89083. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89084. _super.prototype.update.call(this);
  89085. };
  89086. /**
  89087. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89088. * @returns an identity matrix
  89089. */
  89090. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89091. return BABYLON.Matrix.Identity();
  89092. };
  89093. /**
  89094. * This function is called by the two RIG cameras.
  89095. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89096. */
  89097. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89098. var _this = this;
  89099. // Update the parent camera prior to using a child camera to avoid desynchronization
  89100. var parentCamera = this._cameraRigParams["parentCamera"];
  89101. parentCamera._updateCache();
  89102. //WebVR 1.1
  89103. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89104. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89105. if (!this.getScene().useRightHandedSystem) {
  89106. [2, 6, 8, 9, 14].forEach(function (num) {
  89107. _this._webvrViewMatrix.m[num] *= -1;
  89108. });
  89109. }
  89110. // update the camera rotation matrix
  89111. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89112. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89113. // Computing target and final matrix
  89114. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89115. // should the view matrix be updated with scale and position offset?
  89116. if (parentCamera.deviceScaleFactor !== 1) {
  89117. this._webvrViewMatrix.invert();
  89118. // scale the position, if set
  89119. if (parentCamera.deviceScaleFactor) {
  89120. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89121. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89122. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89123. }
  89124. this._webvrViewMatrix.invert();
  89125. }
  89126. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89127. // Compute global position
  89128. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89129. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89130. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89131. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89132. this._markSyncedWithParent();
  89133. return this._webvrViewMatrix;
  89134. };
  89135. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89136. var _this = this;
  89137. var parentCamera = this.parent;
  89138. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89139. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89140. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89141. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89142. //babylon compatible matrix
  89143. if (!this.getScene().useRightHandedSystem) {
  89144. [8, 9, 10, 11].forEach(function (num) {
  89145. _this._projectionMatrix.m[num] *= -1;
  89146. });
  89147. }
  89148. return this._projectionMatrix;
  89149. };
  89150. /**
  89151. * Initializes the controllers and their meshes
  89152. */
  89153. WebVRFreeCamera.prototype.initControllers = function () {
  89154. var _this = this;
  89155. this.controllers = [];
  89156. var manager = this.getScene().gamepadManager;
  89157. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89158. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89159. var webVrController = gamepad;
  89160. if (webVrController.defaultModel) {
  89161. webVrController.defaultModel.setEnabled(false);
  89162. }
  89163. if (webVrController.hand === "right") {
  89164. _this._rightController = null;
  89165. }
  89166. if (webVrController.hand === "left") {
  89167. _this._leftController = null;
  89168. }
  89169. var controllerIndex = _this.controllers.indexOf(webVrController);
  89170. if (controllerIndex !== -1) {
  89171. _this.controllers.splice(controllerIndex, 1);
  89172. }
  89173. }
  89174. });
  89175. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89176. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89177. var webVrController_1 = gamepad;
  89178. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89179. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89180. if (_this.webVROptions.controllerMeshes) {
  89181. if (webVrController_1.defaultModel) {
  89182. webVrController_1.defaultModel.setEnabled(true);
  89183. }
  89184. else {
  89185. // Load the meshes
  89186. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89187. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89188. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89189. if (_this.webVROptions.defaultLightingOnControllers) {
  89190. if (!_this._lightOnControllers) {
  89191. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89192. }
  89193. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89194. var children = mesh.getChildren();
  89195. if (children.length !== 0) {
  89196. children.forEach(function (mesh) {
  89197. light.includedOnlyMeshes.push(mesh);
  89198. activateLightOnSubMeshes_1(mesh, light);
  89199. });
  89200. }
  89201. };
  89202. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89203. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89204. }
  89205. });
  89206. }
  89207. }
  89208. webVrController_1.attachToPoseControlledCamera(_this);
  89209. // since this is async - sanity check. Is the controller already stored?
  89210. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89211. //add to the controllers array
  89212. _this.controllers.push(webVrController_1);
  89213. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89214. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89215. // So we're overriding setting left & right manually to be sure
  89216. var firstViveWandDetected = false;
  89217. for (var i = 0; i < _this.controllers.length; i++) {
  89218. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89219. if (!firstViveWandDetected) {
  89220. firstViveWandDetected = true;
  89221. _this.controllers[i].hand = "left";
  89222. }
  89223. else {
  89224. _this.controllers[i].hand = "right";
  89225. }
  89226. }
  89227. }
  89228. //did we find enough controllers? Great! let the developer know.
  89229. if (_this.controllers.length >= 2) {
  89230. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89231. }
  89232. }
  89233. }
  89234. });
  89235. };
  89236. return WebVRFreeCamera;
  89237. }(BABYLON.FreeCamera));
  89238. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89239. })(BABYLON || (BABYLON = {}));
  89240. //# sourceMappingURL=babylon.webVRCamera.js.map
  89241. var BABYLON;
  89242. (function (BABYLON) {
  89243. // We're mainly based on the logic defined into the FreeCamera code
  89244. /**
  89245. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89246. * being tilted forward or back and left or right.
  89247. */
  89248. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89249. __extends(DeviceOrientationCamera, _super);
  89250. /**
  89251. * Creates a new device orientation camera
  89252. * @param name The name of the camera
  89253. * @param position The start position camera
  89254. * @param scene The scene the camera belongs to
  89255. */
  89256. function DeviceOrientationCamera(name, position, scene) {
  89257. var _this = _super.call(this, name, position, scene) || this;
  89258. _this._quaternionCache = new BABYLON.Quaternion();
  89259. _this.inputs.addDeviceOrientation();
  89260. return _this;
  89261. }
  89262. /**
  89263. * Gets the current instance class name ("DeviceOrientationCamera").
  89264. * This helps avoiding instanceof at run time.
  89265. * @returns the class name
  89266. */
  89267. DeviceOrientationCamera.prototype.getClassName = function () {
  89268. return "DeviceOrientationCamera";
  89269. };
  89270. /**
  89271. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89272. */
  89273. DeviceOrientationCamera.prototype._checkInputs = function () {
  89274. _super.prototype._checkInputs.call(this);
  89275. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89276. if (this._initialQuaternion) {
  89277. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89278. }
  89279. };
  89280. /**
  89281. * Reset the camera to its default orientation on the specified axis only.
  89282. * @param axis The axis to reset
  89283. */
  89284. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89285. var _this = this;
  89286. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89287. //can only work if this camera has a rotation quaternion already.
  89288. if (!this.rotationQuaternion)
  89289. return;
  89290. if (!this._initialQuaternion) {
  89291. this._initialQuaternion = new BABYLON.Quaternion();
  89292. }
  89293. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89294. ['x', 'y', 'z'].forEach(function (axisName) {
  89295. if (!axis[axisName]) {
  89296. _this._initialQuaternion[axisName] = 0;
  89297. }
  89298. else {
  89299. _this._initialQuaternion[axisName] *= -1;
  89300. }
  89301. });
  89302. this._initialQuaternion.normalize();
  89303. //force rotation update
  89304. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89305. };
  89306. return DeviceOrientationCamera;
  89307. }(BABYLON.FreeCamera));
  89308. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89309. })(BABYLON || (BABYLON = {}));
  89310. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89311. var BABYLON;
  89312. (function (BABYLON) {
  89313. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89314. __extends(VRDeviceOrientationFreeCamera, _super);
  89315. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89316. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89317. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89318. var _this = _super.call(this, name, position, scene) || this;
  89319. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89320. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89321. return _this;
  89322. }
  89323. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89324. return "VRDeviceOrientationFreeCamera";
  89325. };
  89326. return VRDeviceOrientationFreeCamera;
  89327. }(BABYLON.DeviceOrientationCamera));
  89328. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89329. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89330. __extends(VRDeviceOrientationGamepadCamera, _super);
  89331. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89332. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89333. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89334. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89335. _this.inputs.addGamepad();
  89336. return _this;
  89337. }
  89338. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89339. return "VRDeviceOrientationGamepadCamera";
  89340. };
  89341. return VRDeviceOrientationGamepadCamera;
  89342. }(VRDeviceOrientationFreeCamera));
  89343. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89344. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89345. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89346. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89347. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89348. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89349. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89350. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89351. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89352. _this.inputs.addVRDeviceOrientation();
  89353. return _this;
  89354. }
  89355. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89356. return "VRDeviceOrientationArcRotateCamera";
  89357. };
  89358. return VRDeviceOrientationArcRotateCamera;
  89359. }(BABYLON.ArcRotateCamera));
  89360. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89361. })(BABYLON || (BABYLON = {}));
  89362. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89363. var BABYLON;
  89364. (function (BABYLON) {
  89365. /**
  89366. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89367. */
  89368. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89369. __extends(AnaglyphFreeCamera, _super);
  89370. /**
  89371. * Creates a new AnaglyphFreeCamera
  89372. * @param name defines camera name
  89373. * @param position defines initial position
  89374. * @param interaxialDistance defines distance between each color axis
  89375. * @param scene defines the hosting scene
  89376. */
  89377. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89378. var _this = _super.call(this, name, position, scene) || this;
  89379. _this.interaxialDistance = interaxialDistance;
  89380. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89381. return _this;
  89382. }
  89383. /**
  89384. * Gets camera class name
  89385. * @returns AnaglyphFreeCamera
  89386. */
  89387. AnaglyphFreeCamera.prototype.getClassName = function () {
  89388. return "AnaglyphFreeCamera";
  89389. };
  89390. return AnaglyphFreeCamera;
  89391. }(BABYLON.FreeCamera));
  89392. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89393. /**
  89394. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89395. */
  89396. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89397. __extends(AnaglyphArcRotateCamera, _super);
  89398. /**
  89399. * Creates a new AnaglyphArcRotateCamera
  89400. * @param name defines camera name
  89401. * @param alpha defines alpha angle (in radians)
  89402. * @param beta defines beta angle (in radians)
  89403. * @param radius defines radius
  89404. * @param target defines camera target
  89405. * @param interaxialDistance defines distance between each color axis
  89406. * @param scene defines the hosting scene
  89407. */
  89408. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89409. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89410. _this.interaxialDistance = interaxialDistance;
  89411. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89412. return _this;
  89413. }
  89414. /**
  89415. * Gets camera class name
  89416. * @returns AnaglyphArcRotateCamera
  89417. */
  89418. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89419. return "AnaglyphArcRotateCamera";
  89420. };
  89421. return AnaglyphArcRotateCamera;
  89422. }(BABYLON.ArcRotateCamera));
  89423. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89424. /**
  89425. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89426. */
  89427. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89428. __extends(AnaglyphGamepadCamera, _super);
  89429. /**
  89430. * Creates a new AnaglyphGamepadCamera
  89431. * @param name defines camera name
  89432. * @param position defines initial position
  89433. * @param interaxialDistance defines distance between each color axis
  89434. * @param scene defines the hosting scene
  89435. */
  89436. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89437. var _this = _super.call(this, name, position, scene) || this;
  89438. _this.interaxialDistance = interaxialDistance;
  89439. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89440. return _this;
  89441. }
  89442. /**
  89443. * Gets camera class name
  89444. * @returns AnaglyphGamepadCamera
  89445. */
  89446. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89447. return "AnaglyphGamepadCamera";
  89448. };
  89449. return AnaglyphGamepadCamera;
  89450. }(BABYLON.GamepadCamera));
  89451. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89452. /**
  89453. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89454. */
  89455. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89456. __extends(AnaglyphUniversalCamera, _super);
  89457. /**
  89458. * Creates a new AnaglyphUniversalCamera
  89459. * @param name defines camera name
  89460. * @param position defines initial position
  89461. * @param interaxialDistance defines distance between each color axis
  89462. * @param scene defines the hosting scene
  89463. */
  89464. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89465. var _this = _super.call(this, name, position, scene) || this;
  89466. _this.interaxialDistance = interaxialDistance;
  89467. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89468. return _this;
  89469. }
  89470. /**
  89471. * Gets camera class name
  89472. * @returns AnaglyphUniversalCamera
  89473. */
  89474. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89475. return "AnaglyphUniversalCamera";
  89476. };
  89477. return AnaglyphUniversalCamera;
  89478. }(BABYLON.UniversalCamera));
  89479. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89480. /**
  89481. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89482. */
  89483. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89484. __extends(StereoscopicFreeCamera, _super);
  89485. /**
  89486. * Creates a new StereoscopicFreeCamera
  89487. * @param name defines camera name
  89488. * @param position defines initial position
  89489. * @param interaxialDistance defines distance between each color axis
  89490. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89491. * @param scene defines the hosting scene
  89492. */
  89493. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89494. var _this = _super.call(this, name, position, scene) || this;
  89495. _this.interaxialDistance = interaxialDistance;
  89496. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89497. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89498. return _this;
  89499. }
  89500. /**
  89501. * Gets camera class name
  89502. * @returns StereoscopicFreeCamera
  89503. */
  89504. StereoscopicFreeCamera.prototype.getClassName = function () {
  89505. return "StereoscopicFreeCamera";
  89506. };
  89507. return StereoscopicFreeCamera;
  89508. }(BABYLON.FreeCamera));
  89509. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89510. /**
  89511. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89512. */
  89513. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89514. __extends(StereoscopicArcRotateCamera, _super);
  89515. /**
  89516. * Creates a new StereoscopicArcRotateCamera
  89517. * @param name defines camera name
  89518. * @param alpha defines alpha angle (in radians)
  89519. * @param beta defines beta angle (in radians)
  89520. * @param radius defines radius
  89521. * @param target defines camera target
  89522. * @param interaxialDistance defines distance between each color axis
  89523. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89524. * @param scene defines the hosting scene
  89525. */
  89526. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89527. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89528. _this.interaxialDistance = interaxialDistance;
  89529. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89530. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89531. return _this;
  89532. }
  89533. /**
  89534. * Gets camera class name
  89535. * @returns StereoscopicArcRotateCamera
  89536. */
  89537. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89538. return "StereoscopicArcRotateCamera";
  89539. };
  89540. return StereoscopicArcRotateCamera;
  89541. }(BABYLON.ArcRotateCamera));
  89542. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89543. /**
  89544. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89545. */
  89546. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89547. __extends(StereoscopicGamepadCamera, _super);
  89548. /**
  89549. * Creates a new StereoscopicGamepadCamera
  89550. * @param name defines camera name
  89551. * @param position defines initial position
  89552. * @param interaxialDistance defines distance between each color axis
  89553. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89554. * @param scene defines the hosting scene
  89555. */
  89556. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89557. var _this = _super.call(this, name, position, scene) || this;
  89558. _this.interaxialDistance = interaxialDistance;
  89559. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89560. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89561. return _this;
  89562. }
  89563. /**
  89564. * Gets camera class name
  89565. * @returns StereoscopicGamepadCamera
  89566. */
  89567. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89568. return "StereoscopicGamepadCamera";
  89569. };
  89570. return StereoscopicGamepadCamera;
  89571. }(BABYLON.GamepadCamera));
  89572. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89573. /**
  89574. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89575. */
  89576. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89577. __extends(StereoscopicUniversalCamera, _super);
  89578. /**
  89579. * Creates a new StereoscopicUniversalCamera
  89580. * @param name defines camera name
  89581. * @param position defines initial position
  89582. * @param interaxialDistance defines distance between each color axis
  89583. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89584. * @param scene defines the hosting scene
  89585. */
  89586. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89587. var _this = _super.call(this, name, position, scene) || this;
  89588. _this.interaxialDistance = interaxialDistance;
  89589. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89590. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89591. return _this;
  89592. }
  89593. /**
  89594. * Gets camera class name
  89595. * @returns StereoscopicUniversalCamera
  89596. */
  89597. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89598. return "StereoscopicUniversalCamera";
  89599. };
  89600. return StereoscopicUniversalCamera;
  89601. }(BABYLON.UniversalCamera));
  89602. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89603. })(BABYLON || (BABYLON = {}));
  89604. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89605. var BABYLON;
  89606. (function (BABYLON) {
  89607. var VRExperienceHelperGazer = /** @class */ (function () {
  89608. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89609. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89610. this.scene = scene;
  89611. this._pointerDownOnMeshAsked = false;
  89612. this._isActionableMesh = false;
  89613. this._teleportationRequestInitiated = false;
  89614. this._teleportationBackRequestInitiated = false;
  89615. this._rotationRightAsked = false;
  89616. this._rotationLeftAsked = false;
  89617. this._dpadPressed = true;
  89618. this._activePointer = false;
  89619. this._id = VRExperienceHelperGazer._idCounter++;
  89620. // Gaze tracker
  89621. if (!gazeTrackerToClone) {
  89622. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  89623. this._gazeTracker.bakeCurrentTransformIntoVertices();
  89624. this._gazeTracker.isPickable = false;
  89625. this._gazeTracker.isVisible = false;
  89626. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  89627. targetMat.specularColor = BABYLON.Color3.Black();
  89628. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89629. targetMat.backFaceCulling = false;
  89630. this._gazeTracker.material = targetMat;
  89631. }
  89632. else {
  89633. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  89634. }
  89635. }
  89636. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  89637. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  89638. };
  89639. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  89640. this._pointerDownOnMeshAsked = true;
  89641. if (this._currentHit) {
  89642. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  89643. }
  89644. };
  89645. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  89646. if (this._currentHit) {
  89647. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  89648. }
  89649. this._pointerDownOnMeshAsked = false;
  89650. };
  89651. VRExperienceHelperGazer.prototype._activatePointer = function () {
  89652. this._activePointer = true;
  89653. };
  89654. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  89655. this._activePointer = false;
  89656. };
  89657. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  89658. if (distance === void 0) { distance = 100; }
  89659. };
  89660. VRExperienceHelperGazer.prototype.dispose = function () {
  89661. this._interactionsEnabled = false;
  89662. this._teleportationEnabled = false;
  89663. if (this._gazeTracker) {
  89664. this._gazeTracker.dispose();
  89665. }
  89666. };
  89667. VRExperienceHelperGazer._idCounter = 0;
  89668. return VRExperienceHelperGazer;
  89669. }());
  89670. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  89671. __extends(VRExperienceHelperControllerGazer, _super);
  89672. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  89673. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  89674. _this.webVRController = webVRController;
  89675. // Laser pointer
  89676. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  89677. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  89678. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89679. laserPointerMaterial.alpha = 0.6;
  89680. _this._laserPointer.material = laserPointerMaterial;
  89681. _this._laserPointer.rotation.x = Math.PI / 2;
  89682. _this._laserPointer.position.z = -0.5;
  89683. _this._laserPointer.isVisible = false;
  89684. if (!webVRController.mesh) {
  89685. // Create an empty mesh that is used prior to loading the high quality model
  89686. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  89687. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  89688. preloadPointerPose.rotation.x = -0.7;
  89689. preloadMesh.addChild(preloadPointerPose);
  89690. webVRController.attachToMesh(preloadMesh);
  89691. }
  89692. _this._setLaserPointerParent(webVRController.mesh);
  89693. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  89694. _this._setLaserPointerParent(mesh);
  89695. });
  89696. return _this;
  89697. }
  89698. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  89699. return this.webVRController.getForwardRay(length);
  89700. };
  89701. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  89702. _super.prototype._activatePointer.call(this);
  89703. this._laserPointer.isVisible = true;
  89704. };
  89705. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  89706. _super.prototype._deactivatePointer.call(this);
  89707. this._laserPointer.isVisible = false;
  89708. };
  89709. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  89710. this._laserPointer.material.emissiveColor = color;
  89711. };
  89712. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  89713. var makeNotPick = function (root) {
  89714. root.name += " laserPointer";
  89715. root.getChildMeshes().forEach(function (c) {
  89716. makeNotPick(c);
  89717. });
  89718. };
  89719. makeNotPick(mesh);
  89720. var childMeshes = mesh.getChildMeshes();
  89721. this.webVRController._pointingPoseNode = null;
  89722. for (var i = 0; i < childMeshes.length; i++) {
  89723. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  89724. mesh = childMeshes[i];
  89725. this.webVRController._pointingPoseNode = mesh;
  89726. break;
  89727. }
  89728. }
  89729. this._laserPointer.parent = mesh;
  89730. };
  89731. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  89732. if (distance === void 0) { distance = 100; }
  89733. this._laserPointer.scaling.y = distance;
  89734. this._laserPointer.position.z = -distance / 2;
  89735. };
  89736. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  89737. _super.prototype.dispose.call(this);
  89738. this._laserPointer.dispose();
  89739. if (this._meshAttachedObserver) {
  89740. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  89741. }
  89742. };
  89743. return VRExperienceHelperControllerGazer;
  89744. }(VRExperienceHelperGazer));
  89745. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  89746. __extends(VRExperienceHelperCameraGazer, _super);
  89747. function VRExperienceHelperCameraGazer(getCamera, scene) {
  89748. var _this = _super.call(this, scene) || this;
  89749. _this.getCamera = getCamera;
  89750. return _this;
  89751. }
  89752. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  89753. var camera = this.getCamera();
  89754. if (camera) {
  89755. return camera.getForwardRay(length);
  89756. }
  89757. else {
  89758. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  89759. }
  89760. };
  89761. return VRExperienceHelperCameraGazer;
  89762. }(VRExperienceHelperGazer));
  89763. /**
  89764. * Helps to quickly add VR support to an existing scene.
  89765. * See http://doc.babylonjs.com/how_to/webvr_helper
  89766. */
  89767. var VRExperienceHelper = /** @class */ (function () {
  89768. /**
  89769. * Instantiates a VRExperienceHelper.
  89770. * Helps to quickly add VR support to an existing scene.
  89771. * @param scene The scene the VRExperienceHelper belongs to.
  89772. * @param webVROptions Options to modify the vr experience helper's behavior.
  89773. */
  89774. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  89775. if (webVROptions === void 0) { webVROptions = {}; }
  89776. var _this = this;
  89777. this.webVROptions = webVROptions;
  89778. // Can the system support WebVR, even if a headset isn't plugged in?
  89779. this._webVRsupported = false;
  89780. // If WebVR is supported, is a headset plugged in and are we ready to present?
  89781. this._webVRready = false;
  89782. // Are we waiting for the requestPresent callback to complete?
  89783. this._webVRrequesting = false;
  89784. // Are we presenting to the headset right now?
  89785. this._webVRpresenting = false;
  89786. // Are we presenting in the fullscreen fallback?
  89787. this._fullscreenVRpresenting = false;
  89788. /**
  89789. * Observable raised when entering VR.
  89790. */
  89791. this.onEnteringVRObservable = new BABYLON.Observable();
  89792. /**
  89793. * Observable raised when exiting VR.
  89794. */
  89795. this.onExitingVRObservable = new BABYLON.Observable();
  89796. /**
  89797. * Observable raised when controller mesh is loaded.
  89798. */
  89799. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89800. this._useCustomVRButton = false;
  89801. this._teleportationRequested = false;
  89802. this._teleportActive = false;
  89803. this._floorMeshesCollection = [];
  89804. this._rotationAllowed = true;
  89805. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  89806. this._isDefaultTeleportationTarget = true;
  89807. this._teleportationFillColor = "#444444";
  89808. this._teleportationBorderColor = "#FFFFFF";
  89809. this._rotationAngle = 0;
  89810. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  89811. this._padSensibilityUp = 0.65;
  89812. this._padSensibilityDown = 0.35;
  89813. this.leftController = null;
  89814. this.rightController = null;
  89815. /**
  89816. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  89817. */
  89818. this.onNewMeshSelected = new BABYLON.Observable();
  89819. /**
  89820. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  89821. */
  89822. this.onNewMeshPicked = new BABYLON.Observable();
  89823. /**
  89824. * Observable raised before camera teleportation
  89825. */
  89826. this.onBeforeCameraTeleport = new BABYLON.Observable();
  89827. /**
  89828. * Observable raised after camera teleportation
  89829. */
  89830. this.onAfterCameraTeleport = new BABYLON.Observable();
  89831. /**
  89832. * Observable raised when current selected mesh gets unselected
  89833. */
  89834. this.onSelectedMeshUnselected = new BABYLON.Observable();
  89835. /**
  89836. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  89837. */
  89838. this.teleportationEnabled = true;
  89839. this._teleportationInitialized = false;
  89840. this._interactionsEnabled = false;
  89841. this._interactionsRequested = false;
  89842. this._displayGaze = true;
  89843. this._displayLaserPointer = true;
  89844. this._onResize = function () {
  89845. _this.moveButtonToBottomRight();
  89846. if (_this._fullscreenVRpresenting && _this._webVRready) {
  89847. _this.exitVR();
  89848. }
  89849. };
  89850. this._onFullscreenChange = function () {
  89851. if (document.fullscreen !== undefined) {
  89852. _this._fullscreenVRpresenting = document.fullscreen;
  89853. }
  89854. else if (document.mozFullScreen !== undefined) {
  89855. _this._fullscreenVRpresenting = document.mozFullScreen;
  89856. }
  89857. else if (document.webkitIsFullScreen !== undefined) {
  89858. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  89859. }
  89860. else if (document.msIsFullScreen !== undefined) {
  89861. _this._fullscreenVRpresenting = document.msIsFullScreen;
  89862. }
  89863. if (!_this._fullscreenVRpresenting && _this._canvas) {
  89864. _this.exitVR();
  89865. if (!_this._useCustomVRButton) {
  89866. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  89867. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  89868. }
  89869. }
  89870. };
  89871. this.beforeRender = function () {
  89872. if (_this.leftController && _this.leftController._activePointer) {
  89873. _this._castRayAndSelectObject(_this.leftController);
  89874. }
  89875. if (_this.rightController && _this.rightController._activePointer) {
  89876. _this._castRayAndSelectObject(_this.rightController);
  89877. }
  89878. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  89879. _this._castRayAndSelectObject(_this._cameraGazer);
  89880. }
  89881. else {
  89882. _this._cameraGazer._gazeTracker.isVisible = false;
  89883. }
  89884. };
  89885. this._onNewGamepadConnected = function (gamepad) {
  89886. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  89887. if (gamepad.leftStick) {
  89888. gamepad.onleftstickchanged(function (stickValues) {
  89889. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  89890. // Listening to classic/xbox gamepad only if no VR controller is active
  89891. if ((!_this.leftController && !_this.rightController) ||
  89892. ((_this.leftController && !_this.leftController._activePointer) &&
  89893. (_this.rightController && !_this.rightController._activePointer))) {
  89894. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  89895. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  89896. }
  89897. }
  89898. });
  89899. }
  89900. if (gamepad.rightStick) {
  89901. gamepad.onrightstickchanged(function (stickValues) {
  89902. if (_this._teleportationInitialized) {
  89903. _this._checkRotate(stickValues, _this._cameraGazer);
  89904. }
  89905. });
  89906. }
  89907. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  89908. gamepad.onbuttondown(function (buttonPressed) {
  89909. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89910. _this._cameraGazer._selectionPointerDown();
  89911. }
  89912. });
  89913. gamepad.onbuttonup(function (buttonPressed) {
  89914. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89915. _this._cameraGazer._selectionPointerUp();
  89916. }
  89917. });
  89918. }
  89919. }
  89920. else {
  89921. var webVRController = gamepad;
  89922. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  89923. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  89924. _this.rightController = controller;
  89925. }
  89926. else {
  89927. _this.leftController = controller;
  89928. }
  89929. _this._tryEnableInteractionOnController(controller);
  89930. }
  89931. };
  89932. // 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
  89933. this._tryEnableInteractionOnController = function (controller) {
  89934. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  89935. _this._enableInteractionOnController(controller);
  89936. }
  89937. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  89938. _this._enableTeleportationOnController(controller);
  89939. }
  89940. };
  89941. this._onNewGamepadDisconnected = function (gamepad) {
  89942. if (gamepad instanceof BABYLON.WebVRController) {
  89943. if (gamepad.hand === "left" && _this.leftController != null) {
  89944. _this.leftController.dispose();
  89945. _this.leftController = null;
  89946. }
  89947. if (gamepad.hand === "right" && _this.rightController != null) {
  89948. _this.rightController.dispose();
  89949. _this.rightController = null;
  89950. }
  89951. }
  89952. };
  89953. this._workingVector = BABYLON.Vector3.Zero();
  89954. this._workingQuaternion = BABYLON.Quaternion.Identity();
  89955. this._workingMatrix = BABYLON.Matrix.Identity();
  89956. this._scene = scene;
  89957. this._canvas = scene.getEngine().getRenderingCanvas();
  89958. // Parse options
  89959. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  89960. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  89961. }
  89962. if (webVROptions.createDeviceOrientationCamera === undefined) {
  89963. webVROptions.createDeviceOrientationCamera = true;
  89964. }
  89965. if (webVROptions.laserToggle === undefined) {
  89966. webVROptions.laserToggle = true;
  89967. }
  89968. if (webVROptions.defaultHeight === undefined) {
  89969. webVROptions.defaultHeight = 1.7;
  89970. }
  89971. if (webVROptions.useCustomVRButton) {
  89972. this._useCustomVRButton = true;
  89973. if (webVROptions.customVRButton) {
  89974. this._btnVR = webVROptions.customVRButton;
  89975. }
  89976. }
  89977. if (webVROptions.rayLength) {
  89978. this._rayLength = webVROptions.rayLength;
  89979. }
  89980. this._defaultHeight = webVROptions.defaultHeight;
  89981. if (webVROptions.positionScale) {
  89982. this._rayLength *= webVROptions.positionScale;
  89983. this._defaultHeight *= webVROptions.positionScale;
  89984. }
  89985. // Set position
  89986. if (this._scene.activeCamera) {
  89987. this._position = this._scene.activeCamera.position.clone();
  89988. }
  89989. else {
  89990. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  89991. }
  89992. // Set non-vr camera
  89993. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  89994. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  89995. // Copy data from existing camera
  89996. if (this._scene.activeCamera) {
  89997. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  89998. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  89999. // Set rotation from previous camera
  90000. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90001. var targetCamera = this._scene.activeCamera;
  90002. if (targetCamera.rotationQuaternion) {
  90003. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90004. }
  90005. else {
  90006. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90007. }
  90008. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90009. }
  90010. }
  90011. this._scene.activeCamera = this._deviceOrientationCamera;
  90012. if (this._canvas) {
  90013. this._scene.activeCamera.attachControl(this._canvas);
  90014. }
  90015. }
  90016. else {
  90017. this._existingCamera = this._scene.activeCamera;
  90018. }
  90019. // Create VR cameras
  90020. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90021. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90022. }
  90023. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90024. this._webVRCamera.useStandingMatrix();
  90025. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90026. // Create default button
  90027. if (!this._useCustomVRButton) {
  90028. this._btnVR = document.createElement("BUTTON");
  90029. this._btnVR.className = "babylonVRicon";
  90030. this._btnVR.id = "babylonVRiconbtn";
  90031. this._btnVR.title = "Click to switch to VR";
  90032. 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) }";
  90033. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90034. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90035. // css += ".babylonVRicon.vrdisplaysupported { }";
  90036. // css += ".babylonVRicon.vrdisplayready { }";
  90037. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90038. var style = document.createElement('style');
  90039. style.appendChild(document.createTextNode(css));
  90040. document.getElementsByTagName('head')[0].appendChild(style);
  90041. this.moveButtonToBottomRight();
  90042. }
  90043. // VR button click event
  90044. if (this._btnVR) {
  90045. this._btnVR.addEventListener("click", function () {
  90046. if (!_this.isInVRMode) {
  90047. _this.enterVR();
  90048. }
  90049. else {
  90050. _this.exitVR();
  90051. }
  90052. });
  90053. }
  90054. // Window events
  90055. window.addEventListener("resize", this._onResize);
  90056. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90057. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90058. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90059. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90060. // Display vr button when headset is connected
  90061. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90062. this.displayVRButton();
  90063. }
  90064. else {
  90065. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90066. if (e.vrDisplay) {
  90067. _this.displayVRButton();
  90068. }
  90069. });
  90070. }
  90071. // Exiting VR mode using 'ESC' key on desktop
  90072. this._onKeyDown = function (event) {
  90073. if (event.keyCode === 27 && _this.isInVRMode) {
  90074. _this.exitVR();
  90075. }
  90076. };
  90077. document.addEventListener("keydown", this._onKeyDown);
  90078. // Exiting VR mode double tapping the touch screen
  90079. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90080. if (_this.isInVRMode) {
  90081. _this.exitVR();
  90082. if (_this._fullscreenVRpresenting) {
  90083. _this._scene.getEngine().switchFullscreen(true);
  90084. }
  90085. }
  90086. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90087. // Listen for WebVR display changes
  90088. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90089. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90090. this._onVRRequestPresentStart = function () {
  90091. _this._webVRrequesting = true;
  90092. _this.updateButtonVisibility();
  90093. };
  90094. this._onVRRequestPresentComplete = function (success) {
  90095. _this._webVRrequesting = false;
  90096. _this.updateButtonVisibility();
  90097. };
  90098. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90099. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90100. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90101. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90102. scene.onDisposeObservable.add(function () {
  90103. _this.dispose();
  90104. });
  90105. // Gamepad connection events
  90106. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90107. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90108. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90109. this.updateButtonVisibility();
  90110. //create easing functions
  90111. this._circleEase = new BABYLON.CircleEase();
  90112. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90113. if (this.webVROptions.floorMeshes) {
  90114. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90115. }
  90116. }
  90117. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90118. /** Return this.onEnteringVRObservable
  90119. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90120. */
  90121. get: function () {
  90122. return this.onEnteringVRObservable;
  90123. },
  90124. enumerable: true,
  90125. configurable: true
  90126. });
  90127. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90128. /** Return this.onExitingVRObservable
  90129. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90130. */
  90131. get: function () {
  90132. return this.onExitingVRObservable;
  90133. },
  90134. enumerable: true,
  90135. configurable: true
  90136. });
  90137. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90138. /** Return this.onControllerMeshLoadedObservable
  90139. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90140. */
  90141. get: function () {
  90142. return this.onControllerMeshLoadedObservable;
  90143. },
  90144. enumerable: true,
  90145. configurable: true
  90146. });
  90147. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90148. /**
  90149. * The mesh used to display where the user is going to teleport.
  90150. */
  90151. get: function () {
  90152. return this._teleportationTarget;
  90153. },
  90154. /**
  90155. * Sets the mesh to be used to display where the user is going to teleport.
  90156. */
  90157. set: function (value) {
  90158. if (value) {
  90159. value.name = "teleportationTarget";
  90160. this._isDefaultTeleportationTarget = false;
  90161. this._teleportationTarget = value;
  90162. }
  90163. },
  90164. enumerable: true,
  90165. configurable: true
  90166. });
  90167. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90168. /**
  90169. * The mesh used to display where the user is selecting,
  90170. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90171. * See http://doc.babylonjs.com/resources/baking_transformations
  90172. */
  90173. get: function () {
  90174. return this._cameraGazer._gazeTracker;
  90175. },
  90176. set: function (value) {
  90177. if (value) {
  90178. this._cameraGazer._gazeTracker = value;
  90179. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90180. this._cameraGazer._gazeTracker.isPickable = false;
  90181. this._cameraGazer._gazeTracker.isVisible = false;
  90182. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90183. if (this.leftController) {
  90184. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90185. }
  90186. if (this.rightController) {
  90187. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90188. }
  90189. }
  90190. },
  90191. enumerable: true,
  90192. configurable: true
  90193. });
  90194. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90195. /**
  90196. * If the ray of the gaze should be displayed.
  90197. */
  90198. get: function () {
  90199. return this._displayGaze;
  90200. },
  90201. /**
  90202. * Sets if the ray of the gaze should be displayed.
  90203. */
  90204. set: function (value) {
  90205. this._displayGaze = value;
  90206. if (!value) {
  90207. this._cameraGazer._gazeTracker.isVisible = false;
  90208. if (this.leftController) {
  90209. this.leftController._gazeTracker.isVisible = false;
  90210. }
  90211. if (this.rightController) {
  90212. this.rightController._gazeTracker.isVisible = false;
  90213. }
  90214. }
  90215. },
  90216. enumerable: true,
  90217. configurable: true
  90218. });
  90219. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90220. /**
  90221. * If the ray of the LaserPointer should be displayed.
  90222. */
  90223. get: function () {
  90224. return this._displayLaserPointer;
  90225. },
  90226. /**
  90227. * Sets if the ray of the LaserPointer should be displayed.
  90228. */
  90229. set: function (value) {
  90230. this._displayLaserPointer = value;
  90231. if (!value) {
  90232. if (this.rightController) {
  90233. this.rightController._deactivatePointer();
  90234. this.rightController._gazeTracker.isVisible = false;
  90235. }
  90236. if (this.leftController) {
  90237. this.leftController._deactivatePointer();
  90238. this.leftController._gazeTracker.isVisible = false;
  90239. }
  90240. }
  90241. else {
  90242. if (this.rightController) {
  90243. this.rightController._activatePointer();
  90244. }
  90245. if (this.leftController) {
  90246. this.leftController._activatePointer();
  90247. }
  90248. }
  90249. },
  90250. enumerable: true,
  90251. configurable: true
  90252. });
  90253. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90254. /**
  90255. * The deviceOrientationCamera used as the camera when not in VR.
  90256. */
  90257. get: function () {
  90258. return this._deviceOrientationCamera;
  90259. },
  90260. enumerable: true,
  90261. configurable: true
  90262. });
  90263. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90264. /**
  90265. * Based on the current WebVR support, returns the current VR camera used.
  90266. */
  90267. get: function () {
  90268. if (this._webVRready) {
  90269. return this._webVRCamera;
  90270. }
  90271. else {
  90272. return this._scene.activeCamera;
  90273. }
  90274. },
  90275. enumerable: true,
  90276. configurable: true
  90277. });
  90278. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90279. /**
  90280. * The webVRCamera which is used when in VR.
  90281. */
  90282. get: function () {
  90283. return this._webVRCamera;
  90284. },
  90285. enumerable: true,
  90286. configurable: true
  90287. });
  90288. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90289. /**
  90290. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90291. */
  90292. get: function () {
  90293. return this._vrDeviceOrientationCamera;
  90294. },
  90295. enumerable: true,
  90296. configurable: true
  90297. });
  90298. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90299. get: function () {
  90300. var result = this._cameraGazer._teleportationRequestInitiated
  90301. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90302. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90303. return result;
  90304. },
  90305. enumerable: true,
  90306. configurable: true
  90307. });
  90308. // Raised when one of the controller has loaded successfully its associated default mesh
  90309. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90310. if (this.leftController && this.leftController.webVRController == webVRController) {
  90311. if (webVRController.mesh) {
  90312. this.leftController._setLaserPointerParent(webVRController.mesh);
  90313. }
  90314. }
  90315. if (this.rightController && this.rightController.webVRController == webVRController) {
  90316. if (webVRController.mesh) {
  90317. this.rightController._setLaserPointerParent(webVRController.mesh);
  90318. }
  90319. }
  90320. try {
  90321. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90322. }
  90323. catch (err) {
  90324. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90325. }
  90326. };
  90327. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90328. /**
  90329. * Gets a value indicating if we are currently in VR mode.
  90330. */
  90331. get: function () {
  90332. return this._webVRpresenting || this._fullscreenVRpresenting;
  90333. },
  90334. enumerable: true,
  90335. configurable: true
  90336. });
  90337. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90338. var vrDisplay = this._scene.getEngine().getVRDevice();
  90339. if (vrDisplay) {
  90340. var wasPresenting = this._webVRpresenting;
  90341. // A VR display is connected
  90342. this._webVRpresenting = vrDisplay.isPresenting;
  90343. if (wasPresenting && !this._webVRpresenting)
  90344. this.exitVR();
  90345. }
  90346. else {
  90347. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90348. }
  90349. this.updateButtonVisibility();
  90350. };
  90351. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90352. this._webVRsupported = eventArgs.vrSupported;
  90353. this._webVRready = !!eventArgs.vrDisplay;
  90354. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90355. this.updateButtonVisibility();
  90356. };
  90357. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90358. if (this._canvas && !this._useCustomVRButton) {
  90359. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90360. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90361. }
  90362. };
  90363. VRExperienceHelper.prototype.displayVRButton = function () {
  90364. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90365. document.body.appendChild(this._btnVR);
  90366. this._btnVRDisplayed = true;
  90367. }
  90368. };
  90369. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90370. if (!this._btnVR || this._useCustomVRButton) {
  90371. return;
  90372. }
  90373. this._btnVR.className = "babylonVRicon";
  90374. if (this.isInVRMode) {
  90375. this._btnVR.className += " vrdisplaypresenting";
  90376. }
  90377. else {
  90378. if (this._webVRready)
  90379. this._btnVR.className += " vrdisplayready";
  90380. if (this._webVRsupported)
  90381. this._btnVR.className += " vrdisplaysupported";
  90382. if (this._webVRrequesting)
  90383. this._btnVR.className += " vrdisplayrequesting";
  90384. }
  90385. };
  90386. /**
  90387. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90388. * Otherwise, will use the fullscreen API.
  90389. */
  90390. VRExperienceHelper.prototype.enterVR = function () {
  90391. if (this.onEnteringVRObservable) {
  90392. try {
  90393. this.onEnteringVRObservable.notifyObservers(this);
  90394. }
  90395. catch (err) {
  90396. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90397. }
  90398. }
  90399. if (this._scene.activeCamera) {
  90400. this._position = this._scene.activeCamera.position.clone();
  90401. // make sure that we return to the last active camera
  90402. this._existingCamera = this._scene.activeCamera;
  90403. }
  90404. if (this._webVRrequesting)
  90405. return;
  90406. // If WebVR is supported and a headset is connected
  90407. if (this._webVRready) {
  90408. if (!this._webVRpresenting) {
  90409. this._webVRCamera.position = this._position;
  90410. this._scene.activeCamera = this._webVRCamera;
  90411. }
  90412. }
  90413. else if (this._vrDeviceOrientationCamera) {
  90414. this._vrDeviceOrientationCamera.position = this._position;
  90415. if (this._scene.activeCamera) {
  90416. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90417. }
  90418. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90419. this._scene.getEngine().switchFullscreen(true);
  90420. this.updateButtonVisibility();
  90421. }
  90422. if (this._scene.activeCamera && this._canvas) {
  90423. this._scene.activeCamera.attachControl(this._canvas);
  90424. }
  90425. if (this._interactionsEnabled) {
  90426. this._scene.registerBeforeRender(this.beforeRender);
  90427. }
  90428. };
  90429. /**
  90430. * Attempt to exit VR, or fullscreen.
  90431. */
  90432. VRExperienceHelper.prototype.exitVR = function () {
  90433. if (this.onExitingVRObservable) {
  90434. try {
  90435. this.onExitingVRObservable.notifyObservers(this);
  90436. }
  90437. catch (err) {
  90438. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90439. }
  90440. }
  90441. if (this._webVRpresenting) {
  90442. this._scene.getEngine().disableVR();
  90443. }
  90444. if (this._scene.activeCamera) {
  90445. this._position = this._scene.activeCamera.position.clone();
  90446. }
  90447. if (this._deviceOrientationCamera) {
  90448. this._deviceOrientationCamera.position = this._position;
  90449. this._scene.activeCamera = this._deviceOrientationCamera;
  90450. if (this._canvas) {
  90451. this._scene.activeCamera.attachControl(this._canvas);
  90452. }
  90453. }
  90454. else if (this._existingCamera) {
  90455. this._existingCamera.position = this._position;
  90456. this._scene.activeCamera = this._existingCamera;
  90457. }
  90458. this.updateButtonVisibility();
  90459. if (this._interactionsEnabled) {
  90460. this._scene.unregisterBeforeRender(this.beforeRender);
  90461. }
  90462. // resize to update width and height when exiting vr exits fullscreen
  90463. this._scene.getEngine().resize();
  90464. };
  90465. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90466. /**
  90467. * The position of the vr experience helper.
  90468. */
  90469. get: function () {
  90470. return this._position;
  90471. },
  90472. /**
  90473. * Sets the position of the vr experience helper.
  90474. */
  90475. set: function (value) {
  90476. this._position = value;
  90477. if (this._scene.activeCamera) {
  90478. this._scene.activeCamera.position = value;
  90479. }
  90480. },
  90481. enumerable: true,
  90482. configurable: true
  90483. });
  90484. /**
  90485. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90486. */
  90487. VRExperienceHelper.prototype.enableInteractions = function () {
  90488. var _this = this;
  90489. if (!this._interactionsEnabled) {
  90490. this._interactionsRequested = true;
  90491. if (this.leftController) {
  90492. this._enableInteractionOnController(this.leftController);
  90493. }
  90494. if (this.rightController) {
  90495. this._enableInteractionOnController(this.rightController);
  90496. }
  90497. this.raySelectionPredicate = function (mesh) {
  90498. return mesh.isVisible;
  90499. };
  90500. this.meshSelectionPredicate = function (mesh) {
  90501. return true;
  90502. };
  90503. this._raySelectionPredicate = function (mesh) {
  90504. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90505. && mesh.name.indexOf("teleportationTarget") === -1
  90506. && mesh.name.indexOf("torusTeleportation") === -1
  90507. && mesh.name.indexOf("laserPointer") === -1)) {
  90508. return _this.raySelectionPredicate(mesh);
  90509. }
  90510. return false;
  90511. };
  90512. this._interactionsEnabled = true;
  90513. }
  90514. };
  90515. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90516. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90517. if (this._floorMeshesCollection[i].id === mesh.id) {
  90518. return true;
  90519. }
  90520. }
  90521. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90522. return true;
  90523. }
  90524. return false;
  90525. };
  90526. /**
  90527. * Adds a floor mesh to be used for teleportation.
  90528. * @param floorMesh the mesh to be used for teleportation.
  90529. */
  90530. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90531. if (!this._floorMeshesCollection) {
  90532. return;
  90533. }
  90534. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90535. return;
  90536. }
  90537. this._floorMeshesCollection.push(floorMesh);
  90538. };
  90539. /**
  90540. * Removes a floor mesh from being used for teleportation.
  90541. * @param floorMesh the mesh to be removed.
  90542. */
  90543. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90544. if (!this._floorMeshesCollection) {
  90545. return;
  90546. }
  90547. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90548. if (meshIndex !== -1) {
  90549. this._floorMeshesCollection.splice(meshIndex, 1);
  90550. }
  90551. };
  90552. /**
  90553. * Enables interactions and teleportation using the VR controllers and gaze.
  90554. * @param vrTeleportationOptions options to modify teleportation behavior.
  90555. */
  90556. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90557. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90558. if (!this._teleportationInitialized) {
  90559. this._teleportationRequested = true;
  90560. this.enableInteractions();
  90561. if (vrTeleportationOptions.floorMeshName) {
  90562. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90563. }
  90564. if (vrTeleportationOptions.floorMeshes) {
  90565. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90566. }
  90567. if (this.leftController != null) {
  90568. this._enableTeleportationOnController(this.leftController);
  90569. }
  90570. if (this.rightController != null) {
  90571. this._enableTeleportationOnController(this.rightController);
  90572. }
  90573. // Creates an image processing post process for the vignette not relying
  90574. // on the main scene configuration for image processing to reduce setup and spaces
  90575. // (gamma/linear) conflicts.
  90576. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90577. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90578. imageProcessingConfiguration.vignetteEnabled = true;
  90579. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90580. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90581. this._teleportationInitialized = true;
  90582. if (this._isDefaultTeleportationTarget) {
  90583. this._createTeleportationCircles();
  90584. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90585. }
  90586. }
  90587. };
  90588. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90589. var _this = this;
  90590. var controllerMesh = controller.webVRController.mesh;
  90591. if (controllerMesh) {
  90592. controller._interactionsEnabled = true;
  90593. controller._activatePointer();
  90594. if (this.webVROptions.laserToggle) {
  90595. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90596. // Enabling / disabling laserPointer
  90597. if (_this._displayLaserPointer && stateObject.value === 1) {
  90598. if (controller._activePointer) {
  90599. controller._deactivatePointer();
  90600. }
  90601. else {
  90602. controller._activatePointer();
  90603. }
  90604. if (_this.displayGaze) {
  90605. controller._gazeTracker.isVisible = controller._activePointer;
  90606. }
  90607. }
  90608. });
  90609. }
  90610. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90611. if (!controller._pointerDownOnMeshAsked) {
  90612. if (stateObject.value > _this._padSensibilityUp) {
  90613. controller._selectionPointerDown();
  90614. }
  90615. }
  90616. else if (stateObject.value < _this._padSensibilityDown) {
  90617. controller._selectionPointerUp();
  90618. }
  90619. });
  90620. }
  90621. };
  90622. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  90623. // Dont teleport if another gaze already requested teleportation
  90624. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  90625. return;
  90626. }
  90627. if (!gazer._teleportationRequestInitiated) {
  90628. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  90629. gazer._activatePointer();
  90630. gazer._teleportationRequestInitiated = true;
  90631. }
  90632. }
  90633. else {
  90634. // Listening to the proper controller values changes to confirm teleportation
  90635. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  90636. if (this._teleportActive) {
  90637. this._teleportCamera(this._haloCenter);
  90638. }
  90639. gazer._teleportationRequestInitiated = false;
  90640. }
  90641. }
  90642. };
  90643. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  90644. // Only rotate when user is not currently selecting a teleportation location
  90645. if (gazer._teleportationRequestInitiated) {
  90646. return;
  90647. }
  90648. if (!gazer._rotationLeftAsked) {
  90649. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  90650. gazer._rotationLeftAsked = true;
  90651. if (this._rotationAllowed) {
  90652. this._rotateCamera(false);
  90653. }
  90654. }
  90655. }
  90656. else {
  90657. if (stateObject.x > -this._padSensibilityDown) {
  90658. gazer._rotationLeftAsked = false;
  90659. }
  90660. }
  90661. if (!gazer._rotationRightAsked) {
  90662. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  90663. gazer._rotationRightAsked = true;
  90664. if (this._rotationAllowed) {
  90665. this._rotateCamera(true);
  90666. }
  90667. }
  90668. }
  90669. else {
  90670. if (stateObject.x < this._padSensibilityDown) {
  90671. gazer._rotationRightAsked = false;
  90672. }
  90673. }
  90674. };
  90675. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  90676. // Only teleport backwards when user is not currently selecting a teleportation location
  90677. if (gazer._teleportationRequestInitiated) {
  90678. return;
  90679. }
  90680. // Teleport backwards
  90681. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  90682. if (!gazer._teleportationBackRequestInitiated) {
  90683. if (!this.currentVRCamera) {
  90684. return;
  90685. }
  90686. // Get rotation and position of the current camera
  90687. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  90688. var position = this.currentVRCamera.position;
  90689. // If the camera has device position, use that instead
  90690. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  90691. rotation = this.currentVRCamera.deviceRotationQuaternion;
  90692. position = this.currentVRCamera.devicePosition;
  90693. }
  90694. // Get matrix with only the y rotation of the device rotation
  90695. rotation.toEulerAnglesToRef(this._workingVector);
  90696. this._workingVector.z = 0;
  90697. this._workingVector.x = 0;
  90698. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  90699. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  90700. // Rotate backwards ray by device rotation to cast at the ground behind the user
  90701. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  90702. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  90703. var ray = new BABYLON.Ray(position, this._workingVector);
  90704. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90705. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  90706. this._teleportCamera(hit.pickedPoint);
  90707. }
  90708. gazer._teleportationBackRequestInitiated = true;
  90709. }
  90710. }
  90711. else {
  90712. gazer._teleportationBackRequestInitiated = false;
  90713. }
  90714. };
  90715. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  90716. var _this = this;
  90717. var controllerMesh = controller.webVRController.mesh;
  90718. if (controllerMesh) {
  90719. if (!controller._interactionsEnabled) {
  90720. this._enableInteractionOnController(controller);
  90721. }
  90722. controller._interactionsEnabled = true;
  90723. controller._teleportationEnabled = true;
  90724. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90725. controller._dpadPressed = false;
  90726. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  90727. controller._dpadPressed = stateObject.pressed;
  90728. if (!controller._dpadPressed) {
  90729. controller._rotationLeftAsked = false;
  90730. controller._rotationRightAsked = false;
  90731. controller._teleportationBackRequestInitiated = false;
  90732. }
  90733. });
  90734. }
  90735. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  90736. if (_this.teleportationEnabled) {
  90737. _this._checkTeleportBackwards(stateObject, controller);
  90738. _this._checkTeleportWithRay(stateObject, controller);
  90739. }
  90740. _this._checkRotate(stateObject, controller);
  90741. });
  90742. }
  90743. };
  90744. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  90745. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  90746. this._teleportationTarget.isPickable = false;
  90747. var length = 512;
  90748. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  90749. dynamicTexture.hasAlpha = true;
  90750. var context = dynamicTexture.getContext();
  90751. var centerX = length / 2;
  90752. var centerY = length / 2;
  90753. var radius = 200;
  90754. context.beginPath();
  90755. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  90756. context.fillStyle = this._teleportationFillColor;
  90757. context.fill();
  90758. context.lineWidth = 10;
  90759. context.strokeStyle = this._teleportationBorderColor;
  90760. context.stroke();
  90761. context.closePath();
  90762. dynamicTexture.update();
  90763. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  90764. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  90765. this._teleportationTarget.material = teleportationCircleMaterial;
  90766. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  90767. torus.isPickable = false;
  90768. torus.parent = this._teleportationTarget;
  90769. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90770. var keys = [];
  90771. keys.push({
  90772. frame: 0,
  90773. value: 0
  90774. });
  90775. keys.push({
  90776. frame: 30,
  90777. value: 0.4
  90778. });
  90779. keys.push({
  90780. frame: 60,
  90781. value: 0
  90782. });
  90783. animationInnerCircle.setKeys(keys);
  90784. var easingFunction = new BABYLON.SineEase();
  90785. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90786. animationInnerCircle.setEasingFunction(easingFunction);
  90787. torus.animations = [];
  90788. torus.animations.push(animationInnerCircle);
  90789. this._scene.beginAnimation(torus, 0, 60, true);
  90790. this._hideTeleportationTarget();
  90791. };
  90792. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  90793. this._teleportActive = true;
  90794. if (this._teleportationInitialized) {
  90795. this._teleportationTarget.isVisible = true;
  90796. if (this._isDefaultTeleportationTarget) {
  90797. this._teleportationTarget.getChildren()[0].isVisible = true;
  90798. }
  90799. }
  90800. };
  90801. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  90802. this._teleportActive = false;
  90803. if (this._teleportationInitialized) {
  90804. this._teleportationTarget.isVisible = false;
  90805. if (this._isDefaultTeleportationTarget) {
  90806. this._teleportationTarget.getChildren()[0].isVisible = false;
  90807. }
  90808. }
  90809. };
  90810. VRExperienceHelper.prototype._rotateCamera = function (right) {
  90811. var _this = this;
  90812. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90813. return;
  90814. }
  90815. if (right) {
  90816. this._rotationAngle++;
  90817. }
  90818. else {
  90819. this._rotationAngle--;
  90820. }
  90821. this.currentVRCamera.animations = [];
  90822. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  90823. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90824. var animationRotationKeys = [];
  90825. animationRotationKeys.push({
  90826. frame: 0,
  90827. value: this.currentVRCamera.rotationQuaternion
  90828. });
  90829. animationRotationKeys.push({
  90830. frame: 6,
  90831. value: target
  90832. });
  90833. animationRotation.setKeys(animationRotationKeys);
  90834. animationRotation.setEasingFunction(this._circleEase);
  90835. this.currentVRCamera.animations.push(animationRotation);
  90836. this._postProcessMove.animations = [];
  90837. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90838. var vignetteWeightKeys = [];
  90839. vignetteWeightKeys.push({
  90840. frame: 0,
  90841. value: 0
  90842. });
  90843. vignetteWeightKeys.push({
  90844. frame: 3,
  90845. value: 4
  90846. });
  90847. vignetteWeightKeys.push({
  90848. frame: 6,
  90849. value: 0
  90850. });
  90851. animationPP.setKeys(vignetteWeightKeys);
  90852. animationPP.setEasingFunction(this._circleEase);
  90853. this._postProcessMove.animations.push(animationPP);
  90854. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90855. var vignetteStretchKeys = [];
  90856. vignetteStretchKeys.push({
  90857. frame: 0,
  90858. value: 0
  90859. });
  90860. vignetteStretchKeys.push({
  90861. frame: 3,
  90862. value: 10
  90863. });
  90864. vignetteStretchKeys.push({
  90865. frame: 6,
  90866. value: 0
  90867. });
  90868. animationPP2.setKeys(vignetteStretchKeys);
  90869. animationPP2.setEasingFunction(this._circleEase);
  90870. this._postProcessMove.animations.push(animationPP2);
  90871. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90872. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90873. this._postProcessMove.samples = 4;
  90874. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90875. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  90876. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90877. });
  90878. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  90879. };
  90880. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  90881. if (hit.pickedPoint) {
  90882. if (gazer._teleportationRequestInitiated) {
  90883. this._displayTeleportationTarget();
  90884. this._haloCenter.copyFrom(hit.pickedPoint);
  90885. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  90886. }
  90887. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  90888. if (pickNormal) {
  90889. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90890. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90891. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  90892. }
  90893. this._teleportationTarget.position.y += 0.1;
  90894. }
  90895. };
  90896. VRExperienceHelper.prototype._teleportCamera = function (location) {
  90897. var _this = this;
  90898. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90899. return;
  90900. }
  90901. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  90902. // offset of the headset from the anchor.
  90903. if (this.webVRCamera.leftCamera) {
  90904. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  90905. this._workingVector.subtractInPlace(this.webVRCamera.position);
  90906. location.subtractToRef(this._workingVector, this._workingVector);
  90907. }
  90908. else {
  90909. this._workingVector.copyFrom(location);
  90910. }
  90911. // Add height to account for user's height offset
  90912. if (this.isInVRMode) {
  90913. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  90914. }
  90915. else {
  90916. this._workingVector.y += this._defaultHeight;
  90917. }
  90918. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  90919. // Create animation from the camera's position to the new location
  90920. this.currentVRCamera.animations = [];
  90921. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90922. var animationCameraTeleportationKeys = [{
  90923. frame: 0,
  90924. value: this.currentVRCamera.position
  90925. },
  90926. {
  90927. frame: 11,
  90928. value: this._workingVector
  90929. }
  90930. ];
  90931. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  90932. animationCameraTeleportation.setEasingFunction(this._circleEase);
  90933. this.currentVRCamera.animations.push(animationCameraTeleportation);
  90934. this._postProcessMove.animations = [];
  90935. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90936. var vignetteWeightKeys = [];
  90937. vignetteWeightKeys.push({
  90938. frame: 0,
  90939. value: 0
  90940. });
  90941. vignetteWeightKeys.push({
  90942. frame: 5,
  90943. value: 8
  90944. });
  90945. vignetteWeightKeys.push({
  90946. frame: 11,
  90947. value: 0
  90948. });
  90949. animationPP.setKeys(vignetteWeightKeys);
  90950. this._postProcessMove.animations.push(animationPP);
  90951. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90952. var vignetteStretchKeys = [];
  90953. vignetteStretchKeys.push({
  90954. frame: 0,
  90955. value: 0
  90956. });
  90957. vignetteStretchKeys.push({
  90958. frame: 5,
  90959. value: 10
  90960. });
  90961. vignetteStretchKeys.push({
  90962. frame: 11,
  90963. value: 0
  90964. });
  90965. animationPP2.setKeys(vignetteStretchKeys);
  90966. this._postProcessMove.animations.push(animationPP2);
  90967. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90968. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90969. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90970. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  90971. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90972. });
  90973. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  90974. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  90975. });
  90976. this._hideTeleportationTarget();
  90977. };
  90978. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  90979. if (normal) {
  90980. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  90981. if (angle < Math.PI / 2) {
  90982. normal.scaleInPlace(-1);
  90983. }
  90984. }
  90985. return normal;
  90986. };
  90987. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  90988. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90989. return;
  90990. }
  90991. var ray = gazer._getForwardRay(this._rayLength);
  90992. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90993. if (hit) {
  90994. // Populate the contrllers mesh that can be used for drag/drop
  90995. if (gazer._laserPointer) {
  90996. hit.originMesh = gazer._laserPointer.parent;
  90997. }
  90998. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  90999. }
  91000. gazer._currentHit = hit;
  91001. // Moving the gazeTracker on the mesh face targetted
  91002. if (hit && hit.pickedPoint) {
  91003. if (this._displayGaze) {
  91004. var multiplier = 1;
  91005. gazer._gazeTracker.isVisible = true;
  91006. if (gazer._isActionableMesh) {
  91007. multiplier = 3;
  91008. }
  91009. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91010. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91011. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91012. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91013. // To avoid z-fighting
  91014. var deltaFighting = 0.002;
  91015. if (pickNormal) {
  91016. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91017. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91018. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91019. }
  91020. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91021. if (gazer._gazeTracker.position.x < 0) {
  91022. gazer._gazeTracker.position.x += deltaFighting;
  91023. }
  91024. else {
  91025. gazer._gazeTracker.position.x -= deltaFighting;
  91026. }
  91027. if (gazer._gazeTracker.position.y < 0) {
  91028. gazer._gazeTracker.position.y += deltaFighting;
  91029. }
  91030. else {
  91031. gazer._gazeTracker.position.y -= deltaFighting;
  91032. }
  91033. if (gazer._gazeTracker.position.z < 0) {
  91034. gazer._gazeTracker.position.z += deltaFighting;
  91035. }
  91036. else {
  91037. gazer._gazeTracker.position.z -= deltaFighting;
  91038. }
  91039. }
  91040. // Changing the size of the laser pointer based on the distance from the targetted point
  91041. gazer._updatePointerDistance(hit.distance);
  91042. }
  91043. else {
  91044. gazer._updatePointerDistance();
  91045. gazer._gazeTracker.isVisible = false;
  91046. }
  91047. if (hit && hit.pickedMesh) {
  91048. // The object selected is the floor, we're in a teleportation scenario
  91049. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91050. // Moving the teleportation area to this targetted point
  91051. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91052. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91053. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91054. }
  91055. gazer._currentMeshSelected = null;
  91056. if (gazer._teleportationRequestInitiated) {
  91057. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91058. }
  91059. return;
  91060. }
  91061. // If not, we're in a selection scenario
  91062. //this._teleportationAllowed = false;
  91063. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91064. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91065. this.onNewMeshPicked.notifyObservers(hit);
  91066. gazer._currentMeshSelected = hit.pickedMesh;
  91067. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91068. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91069. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91070. gazer._isActionableMesh = true;
  91071. }
  91072. else {
  91073. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91074. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91075. gazer._isActionableMesh = false;
  91076. }
  91077. try {
  91078. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91079. }
  91080. catch (err) {
  91081. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91082. }
  91083. }
  91084. else {
  91085. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91086. gazer._currentMeshSelected = null;
  91087. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91088. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91089. }
  91090. }
  91091. }
  91092. else {
  91093. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91094. gazer._currentMeshSelected = null;
  91095. //this._teleportationAllowed = false;
  91096. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91097. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91098. }
  91099. };
  91100. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91101. if (mesh) {
  91102. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91103. }
  91104. };
  91105. /**
  91106. * Sets the color of the laser ray from the vr controllers.
  91107. * @param color new color for the ray.
  91108. */
  91109. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91110. if (this.leftController) {
  91111. this.leftController._setLaserPointerColor(color);
  91112. }
  91113. if (this.rightController) {
  91114. this.rightController._setLaserPointerColor(color);
  91115. }
  91116. };
  91117. /**
  91118. * Sets the color of the ray from the vr headsets gaze.
  91119. * @param color new color for the ray.
  91120. */
  91121. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91122. if (!this._cameraGazer._gazeTracker.material) {
  91123. return;
  91124. }
  91125. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91126. if (this.leftController) {
  91127. this.leftController._gazeTracker.material.emissiveColor = color;
  91128. }
  91129. if (this.rightController) {
  91130. this.rightController._gazeTracker.material.emissiveColor = color;
  91131. }
  91132. };
  91133. /**
  91134. * Exits VR and disposes of the vr experience helper
  91135. */
  91136. VRExperienceHelper.prototype.dispose = function () {
  91137. if (this.isInVRMode) {
  91138. this.exitVR();
  91139. }
  91140. if (this._postProcessMove) {
  91141. this._postProcessMove.dispose();
  91142. }
  91143. if (this._webVRCamera) {
  91144. this._webVRCamera.dispose();
  91145. }
  91146. if (this._vrDeviceOrientationCamera) {
  91147. this._vrDeviceOrientationCamera.dispose();
  91148. }
  91149. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91150. document.body.removeChild(this._btnVR);
  91151. }
  91152. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91153. this._deviceOrientationCamera.dispose();
  91154. }
  91155. if (this._cameraGazer) {
  91156. this._cameraGazer.dispose();
  91157. }
  91158. if (this.leftController) {
  91159. this.leftController.dispose();
  91160. }
  91161. if (this.rightController) {
  91162. this.rightController.dispose();
  91163. }
  91164. if (this._teleportationTarget) {
  91165. this._teleportationTarget.dispose();
  91166. }
  91167. this._floorMeshesCollection = [];
  91168. document.removeEventListener("keydown", this._onKeyDown);
  91169. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91170. window.removeEventListener("resize", this._onResize);
  91171. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91172. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91173. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91174. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91175. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91176. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91177. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91178. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91179. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91180. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91181. this._scene.unregisterBeforeRender(this.beforeRender);
  91182. };
  91183. /**
  91184. * Gets the name of the VRExperienceHelper class
  91185. * @returns "VRExperienceHelper"
  91186. */
  91187. VRExperienceHelper.prototype.getClassName = function () {
  91188. return "VRExperienceHelper";
  91189. };
  91190. return VRExperienceHelper;
  91191. }());
  91192. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91193. })(BABYLON || (BABYLON = {}));
  91194. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91195. // Mainly based on these 2 articles :
  91196. // 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
  91197. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91198. var BABYLON;
  91199. (function (BABYLON) {
  91200. /**
  91201. * Defines the potential axis of a Joystick
  91202. */
  91203. var JoystickAxis;
  91204. (function (JoystickAxis) {
  91205. /** X axis */
  91206. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91207. /** Y axis */
  91208. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91209. /** Z axis */
  91210. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91211. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91212. /**
  91213. * Class used to define virtual joystick (used in touch mode)
  91214. */
  91215. var VirtualJoystick = /** @class */ (function () {
  91216. /**
  91217. * Creates a new virtual joystick
  91218. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91219. */
  91220. function VirtualJoystick(leftJoystick) {
  91221. var _this = this;
  91222. if (leftJoystick) {
  91223. this._leftJoystick = true;
  91224. }
  91225. else {
  91226. this._leftJoystick = false;
  91227. }
  91228. VirtualJoystick._globalJoystickIndex++;
  91229. // By default left & right arrow keys are moving the X
  91230. // and up & down keys are moving the Y
  91231. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91232. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91233. this.reverseLeftRight = false;
  91234. this.reverseUpDown = false;
  91235. // collections of pointers
  91236. this._touches = new BABYLON.StringDictionary();
  91237. this.deltaPosition = BABYLON.Vector3.Zero();
  91238. this._joystickSensibility = 25;
  91239. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91240. this._onResize = function (evt) {
  91241. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91242. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91243. if (VirtualJoystick.vjCanvas) {
  91244. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91245. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91246. }
  91247. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91248. };
  91249. // injecting a canvas element on top of the canvas 3D game
  91250. if (!VirtualJoystick.vjCanvas) {
  91251. window.addEventListener("resize", this._onResize, false);
  91252. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91253. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91254. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91255. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91256. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91257. VirtualJoystick.vjCanvas.style.width = "100%";
  91258. VirtualJoystick.vjCanvas.style.height = "100%";
  91259. VirtualJoystick.vjCanvas.style.position = "absolute";
  91260. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91261. VirtualJoystick.vjCanvas.style.top = "0px";
  91262. VirtualJoystick.vjCanvas.style.left = "0px";
  91263. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91264. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91265. // Support for jQuery PEP polyfill
  91266. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91267. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91268. if (!context) {
  91269. throw new Error("Unable to create canvas for virtual joystick");
  91270. }
  91271. VirtualJoystick.vjCanvasContext = context;
  91272. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91273. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91274. document.body.appendChild(VirtualJoystick.vjCanvas);
  91275. }
  91276. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91277. this.pressed = false;
  91278. // default joystick color
  91279. this._joystickColor = "cyan";
  91280. this._joystickPointerID = -1;
  91281. // current joystick position
  91282. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91283. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91284. // origin joystick position
  91285. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91286. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91287. this._onPointerDownHandlerRef = function (evt) {
  91288. _this._onPointerDown(evt);
  91289. };
  91290. this._onPointerMoveHandlerRef = function (evt) {
  91291. _this._onPointerMove(evt);
  91292. };
  91293. this._onPointerUpHandlerRef = function (evt) {
  91294. _this._onPointerUp(evt);
  91295. };
  91296. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91297. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91298. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91299. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91300. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91301. evt.preventDefault(); // Disables system menu
  91302. }, false);
  91303. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91304. }
  91305. /**
  91306. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91307. * @param newJoystickSensibility defines the new sensibility
  91308. */
  91309. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91310. this._joystickSensibility = newJoystickSensibility;
  91311. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91312. };
  91313. VirtualJoystick.prototype._onPointerDown = function (e) {
  91314. var positionOnScreenCondition;
  91315. e.preventDefault();
  91316. if (this._leftJoystick === true) {
  91317. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91318. }
  91319. else {
  91320. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91321. }
  91322. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91323. // First contact will be dedicated to the virtual joystick
  91324. this._joystickPointerID = e.pointerId;
  91325. this._joystickPointerStartPos.x = e.clientX;
  91326. this._joystickPointerStartPos.y = e.clientY;
  91327. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91328. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91329. this._deltaJoystickVector.x = 0;
  91330. this._deltaJoystickVector.y = 0;
  91331. this.pressed = true;
  91332. this._touches.add(e.pointerId.toString(), e);
  91333. }
  91334. else {
  91335. // You can only trigger the action buttons with a joystick declared
  91336. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91337. this._action();
  91338. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91339. }
  91340. }
  91341. };
  91342. VirtualJoystick.prototype._onPointerMove = function (e) {
  91343. // If the current pointer is the one associated to the joystick (first touch contact)
  91344. if (this._joystickPointerID == e.pointerId) {
  91345. this._joystickPointerPos.x = e.clientX;
  91346. this._joystickPointerPos.y = e.clientY;
  91347. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91348. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91349. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91350. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91351. switch (this._axisTargetedByLeftAndRight) {
  91352. case JoystickAxis.X:
  91353. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91354. break;
  91355. case JoystickAxis.Y:
  91356. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91357. break;
  91358. case JoystickAxis.Z:
  91359. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91360. break;
  91361. }
  91362. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91363. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91364. switch (this._axisTargetedByUpAndDown) {
  91365. case JoystickAxis.X:
  91366. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91367. break;
  91368. case JoystickAxis.Y:
  91369. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91370. break;
  91371. case JoystickAxis.Z:
  91372. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91373. break;
  91374. }
  91375. }
  91376. else {
  91377. var data = this._touches.get(e.pointerId.toString());
  91378. if (data) {
  91379. data.x = e.clientX;
  91380. data.y = e.clientY;
  91381. }
  91382. }
  91383. };
  91384. VirtualJoystick.prototype._onPointerUp = function (e) {
  91385. if (this._joystickPointerID == e.pointerId) {
  91386. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91387. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91388. this._joystickPointerID = -1;
  91389. this.pressed = false;
  91390. }
  91391. else {
  91392. var touch = this._touches.get(e.pointerId.toString());
  91393. if (touch) {
  91394. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91395. }
  91396. }
  91397. this._deltaJoystickVector.x = 0;
  91398. this._deltaJoystickVector.y = 0;
  91399. this._touches.remove(e.pointerId.toString());
  91400. };
  91401. /**
  91402. * Change the color of the virtual joystick
  91403. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91404. */
  91405. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91406. this._joystickColor = newColor;
  91407. };
  91408. /**
  91409. * Defines a callback to call when the joystick is touched
  91410. * @param action defines the callback
  91411. */
  91412. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91413. this._action = action;
  91414. };
  91415. /**
  91416. * Defines which axis you'd like to control for left & right
  91417. * @param axis defines the axis to use
  91418. */
  91419. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91420. switch (axis) {
  91421. case JoystickAxis.X:
  91422. case JoystickAxis.Y:
  91423. case JoystickAxis.Z:
  91424. this._axisTargetedByLeftAndRight = axis;
  91425. break;
  91426. default:
  91427. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91428. break;
  91429. }
  91430. };
  91431. /**
  91432. * Defines which axis you'd like to control for up & down
  91433. * @param axis defines the axis to use
  91434. */
  91435. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91436. switch (axis) {
  91437. case JoystickAxis.X:
  91438. case JoystickAxis.Y:
  91439. case JoystickAxis.Z:
  91440. this._axisTargetedByUpAndDown = axis;
  91441. break;
  91442. default:
  91443. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91444. break;
  91445. }
  91446. };
  91447. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91448. var _this = this;
  91449. if (this.pressed) {
  91450. this._touches.forEach(function (key, touch) {
  91451. if (touch.pointerId === _this._joystickPointerID) {
  91452. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91453. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91454. VirtualJoystick.vjCanvasContext.beginPath();
  91455. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91456. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91457. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91458. VirtualJoystick.vjCanvasContext.stroke();
  91459. VirtualJoystick.vjCanvasContext.closePath();
  91460. VirtualJoystick.vjCanvasContext.beginPath();
  91461. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91462. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91463. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91464. VirtualJoystick.vjCanvasContext.stroke();
  91465. VirtualJoystick.vjCanvasContext.closePath();
  91466. VirtualJoystick.vjCanvasContext.beginPath();
  91467. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91468. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91469. VirtualJoystick.vjCanvasContext.stroke();
  91470. VirtualJoystick.vjCanvasContext.closePath();
  91471. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91472. }
  91473. else {
  91474. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91475. VirtualJoystick.vjCanvasContext.beginPath();
  91476. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91477. VirtualJoystick.vjCanvasContext.beginPath();
  91478. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91479. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91480. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91481. VirtualJoystick.vjCanvasContext.stroke();
  91482. VirtualJoystick.vjCanvasContext.closePath();
  91483. touch.prevX = touch.x;
  91484. touch.prevY = touch.y;
  91485. }
  91486. ;
  91487. });
  91488. }
  91489. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91490. };
  91491. /**
  91492. * Release internal HTML canvas
  91493. */
  91494. VirtualJoystick.prototype.releaseCanvas = function () {
  91495. if (VirtualJoystick.vjCanvas) {
  91496. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91497. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91498. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91499. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91500. window.removeEventListener("resize", this._onResize);
  91501. document.body.removeChild(VirtualJoystick.vjCanvas);
  91502. VirtualJoystick.vjCanvas = null;
  91503. }
  91504. };
  91505. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91506. VirtualJoystick._globalJoystickIndex = 0;
  91507. return VirtualJoystick;
  91508. }());
  91509. BABYLON.VirtualJoystick = VirtualJoystick;
  91510. })(BABYLON || (BABYLON = {}));
  91511. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91512. var BABYLON;
  91513. (function (BABYLON) {
  91514. // We're mainly based on the logic defined into the FreeCamera code
  91515. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91516. __extends(VirtualJoysticksCamera, _super);
  91517. function VirtualJoysticksCamera(name, position, scene) {
  91518. var _this = _super.call(this, name, position, scene) || this;
  91519. _this.inputs.addVirtualJoystick();
  91520. return _this;
  91521. }
  91522. VirtualJoysticksCamera.prototype.getClassName = function () {
  91523. return "VirtualJoysticksCamera";
  91524. };
  91525. return VirtualJoysticksCamera;
  91526. }(BABYLON.FreeCamera));
  91527. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91528. })(BABYLON || (BABYLON = {}));
  91529. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91530. var BABYLON;
  91531. (function (BABYLON) {
  91532. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91533. function FreeCameraVirtualJoystickInput() {
  91534. }
  91535. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91536. return this._leftjoystick;
  91537. };
  91538. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91539. return this._rightjoystick;
  91540. };
  91541. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91542. if (this._leftjoystick) {
  91543. var camera = this.camera;
  91544. var speed = camera._computeLocalCameraSpeed() * 50;
  91545. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91546. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91547. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91548. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91549. if (!this._leftjoystick.pressed) {
  91550. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91551. }
  91552. if (!this._rightjoystick.pressed) {
  91553. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91554. }
  91555. }
  91556. };
  91557. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91558. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91559. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91560. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91561. this._leftjoystick.setJoystickSensibility(0.15);
  91562. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91563. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91564. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91565. this._rightjoystick.reverseUpDown = true;
  91566. this._rightjoystick.setJoystickSensibility(0.05);
  91567. this._rightjoystick.setJoystickColor("yellow");
  91568. };
  91569. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91570. this._leftjoystick.releaseCanvas();
  91571. this._rightjoystick.releaseCanvas();
  91572. };
  91573. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91574. return "FreeCameraVirtualJoystickInput";
  91575. };
  91576. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91577. return "virtualJoystick";
  91578. };
  91579. return FreeCameraVirtualJoystickInput;
  91580. }());
  91581. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91582. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91583. })(BABYLON || (BABYLON = {}));
  91584. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91585. var BABYLON;
  91586. (function (BABYLON) {
  91587. var SimplificationSettings = /** @class */ (function () {
  91588. function SimplificationSettings(quality, distance, optimizeMesh) {
  91589. this.quality = quality;
  91590. this.distance = distance;
  91591. this.optimizeMesh = optimizeMesh;
  91592. }
  91593. return SimplificationSettings;
  91594. }());
  91595. BABYLON.SimplificationSettings = SimplificationSettings;
  91596. var SimplificationQueue = /** @class */ (function () {
  91597. function SimplificationQueue() {
  91598. this.running = false;
  91599. this._simplificationArray = [];
  91600. }
  91601. SimplificationQueue.prototype.addTask = function (task) {
  91602. this._simplificationArray.push(task);
  91603. };
  91604. SimplificationQueue.prototype.executeNext = function () {
  91605. var task = this._simplificationArray.pop();
  91606. if (task) {
  91607. this.running = true;
  91608. this.runSimplification(task);
  91609. }
  91610. else {
  91611. this.running = false;
  91612. }
  91613. };
  91614. SimplificationQueue.prototype.runSimplification = function (task) {
  91615. var _this = this;
  91616. if (task.parallelProcessing) {
  91617. //parallel simplifier
  91618. task.settings.forEach(function (setting) {
  91619. var simplifier = _this.getSimplifier(task);
  91620. simplifier.simplify(setting, function (newMesh) {
  91621. task.mesh.addLODLevel(setting.distance, newMesh);
  91622. newMesh.isVisible = true;
  91623. //check if it is the last
  91624. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  91625. //all done, run the success callback.
  91626. task.successCallback();
  91627. }
  91628. _this.executeNext();
  91629. });
  91630. });
  91631. }
  91632. else {
  91633. //single simplifier.
  91634. var simplifier = this.getSimplifier(task);
  91635. var runDecimation = function (setting, callback) {
  91636. simplifier.simplify(setting, function (newMesh) {
  91637. task.mesh.addLODLevel(setting.distance, newMesh);
  91638. newMesh.isVisible = true;
  91639. //run the next quality level
  91640. callback();
  91641. });
  91642. };
  91643. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  91644. runDecimation(task.settings[loop.index], function () {
  91645. loop.executeNext();
  91646. });
  91647. }, function () {
  91648. //execution ended, run the success callback.
  91649. if (task.successCallback) {
  91650. task.successCallback();
  91651. }
  91652. _this.executeNext();
  91653. });
  91654. }
  91655. };
  91656. SimplificationQueue.prototype.getSimplifier = function (task) {
  91657. switch (task.simplificationType) {
  91658. case SimplificationType.QUADRATIC:
  91659. default:
  91660. return new QuadraticErrorSimplification(task.mesh);
  91661. }
  91662. };
  91663. return SimplificationQueue;
  91664. }());
  91665. BABYLON.SimplificationQueue = SimplificationQueue;
  91666. /**
  91667. * The implemented types of simplification
  91668. * At the moment only Quadratic Error Decimation is implemented
  91669. */
  91670. var SimplificationType;
  91671. (function (SimplificationType) {
  91672. /** Quadratic error decimation */
  91673. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  91674. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  91675. var DecimationTriangle = /** @class */ (function () {
  91676. function DecimationTriangle(vertices) {
  91677. this.vertices = vertices;
  91678. this.error = new Array(4);
  91679. this.deleted = false;
  91680. this.isDirty = false;
  91681. this.deletePending = false;
  91682. this.borderFactor = 0;
  91683. }
  91684. return DecimationTriangle;
  91685. }());
  91686. BABYLON.DecimationTriangle = DecimationTriangle;
  91687. var DecimationVertex = /** @class */ (function () {
  91688. function DecimationVertex(position, id) {
  91689. this.position = position;
  91690. this.id = id;
  91691. this.isBorder = true;
  91692. this.q = new QuadraticMatrix();
  91693. this.triangleCount = 0;
  91694. this.triangleStart = 0;
  91695. this.originalOffsets = [];
  91696. }
  91697. DecimationVertex.prototype.updatePosition = function (newPosition) {
  91698. this.position.copyFrom(newPosition);
  91699. };
  91700. return DecimationVertex;
  91701. }());
  91702. BABYLON.DecimationVertex = DecimationVertex;
  91703. var QuadraticMatrix = /** @class */ (function () {
  91704. function QuadraticMatrix(data) {
  91705. this.data = new Array(10);
  91706. for (var i = 0; i < 10; ++i) {
  91707. if (data && data[i]) {
  91708. this.data[i] = data[i];
  91709. }
  91710. else {
  91711. this.data[i] = 0;
  91712. }
  91713. }
  91714. }
  91715. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  91716. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  91717. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  91718. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  91719. return det;
  91720. };
  91721. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  91722. for (var i = 0; i < 10; ++i) {
  91723. this.data[i] += matrix.data[i];
  91724. }
  91725. };
  91726. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  91727. for (var i = 0; i < 10; ++i) {
  91728. this.data[i] += data[i];
  91729. }
  91730. };
  91731. QuadraticMatrix.prototype.add = function (matrix) {
  91732. var m = new QuadraticMatrix();
  91733. for (var i = 0; i < 10; ++i) {
  91734. m.data[i] = this.data[i] + matrix.data[i];
  91735. }
  91736. return m;
  91737. };
  91738. QuadraticMatrix.FromData = function (a, b, c, d) {
  91739. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  91740. };
  91741. //returning an array to avoid garbage collection
  91742. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  91743. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  91744. };
  91745. return QuadraticMatrix;
  91746. }());
  91747. BABYLON.QuadraticMatrix = QuadraticMatrix;
  91748. var Reference = /** @class */ (function () {
  91749. function Reference(vertexId, triangleId) {
  91750. this.vertexId = vertexId;
  91751. this.triangleId = triangleId;
  91752. }
  91753. return Reference;
  91754. }());
  91755. BABYLON.Reference = Reference;
  91756. /**
  91757. * An implementation of the Quadratic Error simplification algorithm.
  91758. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  91759. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  91760. * @author RaananW
  91761. */
  91762. var QuadraticErrorSimplification = /** @class */ (function () {
  91763. function QuadraticErrorSimplification(_mesh) {
  91764. this._mesh = _mesh;
  91765. this.syncIterations = 5000;
  91766. this.aggressiveness = 7;
  91767. this.decimationIterations = 100;
  91768. this.boundingBoxEpsilon = BABYLON.Epsilon;
  91769. }
  91770. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  91771. var _this = this;
  91772. this.initDecimatedMesh();
  91773. //iterating through the submeshes array, one after the other.
  91774. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  91775. _this.initWithMesh(loop.index, function () {
  91776. _this.runDecimation(settings, loop.index, function () {
  91777. loop.executeNext();
  91778. });
  91779. }, settings.optimizeMesh);
  91780. }, function () {
  91781. setTimeout(function () {
  91782. successCallback(_this._reconstructedMesh);
  91783. }, 0);
  91784. });
  91785. };
  91786. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  91787. var _this = this;
  91788. var targetCount = ~~(this.triangles.length * settings.quality);
  91789. var deletedTriangles = 0;
  91790. var triangleCount = this.triangles.length;
  91791. var iterationFunction = function (iteration, callback) {
  91792. setTimeout(function () {
  91793. if (iteration % 5 === 0) {
  91794. _this.updateMesh(iteration === 0);
  91795. }
  91796. for (var i = 0; i < _this.triangles.length; ++i) {
  91797. _this.triangles[i].isDirty = false;
  91798. }
  91799. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  91800. var trianglesIterator = function (i) {
  91801. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  91802. var t = _this.triangles[tIdx];
  91803. if (!t)
  91804. return;
  91805. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  91806. return;
  91807. }
  91808. for (var j = 0; j < 3; ++j) {
  91809. if (t.error[j] < threshold) {
  91810. var deleted0 = [];
  91811. var deleted1 = [];
  91812. var v0 = t.vertices[j];
  91813. var v1 = t.vertices[(j + 1) % 3];
  91814. if (v0.isBorder || v1.isBorder)
  91815. continue;
  91816. var p = BABYLON.Vector3.Zero();
  91817. var n = BABYLON.Vector3.Zero();
  91818. var uv = BABYLON.Vector2.Zero();
  91819. var color = new BABYLON.Color4(0, 0, 0, 1);
  91820. _this.calculateError(v0, v1, p, n, uv, color);
  91821. var delTr = new Array();
  91822. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  91823. continue;
  91824. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  91825. continue;
  91826. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  91827. continue;
  91828. var uniqueArray = new Array();
  91829. delTr.forEach(function (deletedT) {
  91830. if (uniqueArray.indexOf(deletedT) === -1) {
  91831. deletedT.deletePending = true;
  91832. uniqueArray.push(deletedT);
  91833. }
  91834. });
  91835. if (uniqueArray.length % 2 !== 0) {
  91836. continue;
  91837. }
  91838. v0.q = v1.q.add(v0.q);
  91839. v0.updatePosition(p);
  91840. var tStart = _this.references.length;
  91841. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  91842. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  91843. var tCount = _this.references.length - tStart;
  91844. if (tCount <= v0.triangleCount) {
  91845. if (tCount) {
  91846. for (var c = 0; c < tCount; c++) {
  91847. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  91848. }
  91849. }
  91850. }
  91851. else {
  91852. v0.triangleStart = tStart;
  91853. }
  91854. v0.triangleCount = tCount;
  91855. break;
  91856. }
  91857. }
  91858. };
  91859. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  91860. }, 0);
  91861. };
  91862. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  91863. if (triangleCount - deletedTriangles <= targetCount)
  91864. loop.breakLoop();
  91865. else {
  91866. iterationFunction(loop.index, function () {
  91867. loop.executeNext();
  91868. });
  91869. }
  91870. }, function () {
  91871. setTimeout(function () {
  91872. //reconstruct this part of the mesh
  91873. _this.reconstructMesh(submeshIndex);
  91874. successCallback();
  91875. }, 0);
  91876. });
  91877. };
  91878. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  91879. var _this = this;
  91880. this.vertices = [];
  91881. this.triangles = [];
  91882. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91883. var indices = this._mesh.getIndices();
  91884. var submesh = this._mesh.subMeshes[submeshIndex];
  91885. var findInVertices = function (positionToSearch) {
  91886. if (optimizeMesh) {
  91887. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  91888. if (_this.vertices[ii].position.equals(positionToSearch)) {
  91889. return _this.vertices[ii];
  91890. }
  91891. }
  91892. }
  91893. return null;
  91894. };
  91895. var vertexReferences = [];
  91896. var vertexInit = function (i) {
  91897. if (!positionData) {
  91898. return;
  91899. }
  91900. var offset = i + submesh.verticesStart;
  91901. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  91902. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  91903. vertex.originalOffsets.push(offset);
  91904. if (vertex.id === _this.vertices.length) {
  91905. _this.vertices.push(vertex);
  91906. }
  91907. vertexReferences.push(vertex.id);
  91908. };
  91909. //var totalVertices = mesh.getTotalVertices();
  91910. var totalVertices = submesh.verticesCount;
  91911. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  91912. var indicesInit = function (i) {
  91913. if (!indices) {
  91914. return;
  91915. }
  91916. var offset = (submesh.indexStart / 3) + i;
  91917. var pos = (offset * 3);
  91918. var i0 = indices[pos + 0];
  91919. var i1 = indices[pos + 1];
  91920. var i2 = indices[pos + 2];
  91921. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  91922. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  91923. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  91924. var triangle = new DecimationTriangle([v0, v1, v2]);
  91925. triangle.originalOffset = pos;
  91926. _this.triangles.push(triangle);
  91927. };
  91928. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  91929. _this.init(callback);
  91930. });
  91931. });
  91932. };
  91933. QuadraticErrorSimplification.prototype.init = function (callback) {
  91934. var _this = this;
  91935. var triangleInit1 = function (i) {
  91936. var t = _this.triangles[i];
  91937. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  91938. for (var j = 0; j < 3; j++) {
  91939. 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))));
  91940. }
  91941. };
  91942. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  91943. var triangleInit2 = function (i) {
  91944. var t = _this.triangles[i];
  91945. for (var j = 0; j < 3; ++j) {
  91946. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  91947. }
  91948. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  91949. };
  91950. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  91951. callback();
  91952. });
  91953. });
  91954. };
  91955. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  91956. var newTriangles = [];
  91957. var i;
  91958. for (i = 0; i < this.vertices.length; ++i) {
  91959. this.vertices[i].triangleCount = 0;
  91960. }
  91961. var t;
  91962. var j;
  91963. for (i = 0; i < this.triangles.length; ++i) {
  91964. if (!this.triangles[i].deleted) {
  91965. t = this.triangles[i];
  91966. for (j = 0; j < 3; ++j) {
  91967. t.vertices[j].triangleCount = 1;
  91968. }
  91969. newTriangles.push(t);
  91970. }
  91971. }
  91972. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  91973. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  91974. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  91975. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  91976. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  91977. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  91978. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  91979. var vertexCount = 0;
  91980. for (i = 0; i < this.vertices.length; ++i) {
  91981. var vertex = this.vertices[i];
  91982. vertex.id = vertexCount;
  91983. if (vertex.triangleCount) {
  91984. vertex.originalOffsets.forEach(function (originalOffset) {
  91985. if (!normalData) {
  91986. return;
  91987. }
  91988. newPositionData.push(vertex.position.x);
  91989. newPositionData.push(vertex.position.y);
  91990. newPositionData.push(vertex.position.z);
  91991. newNormalData.push(normalData[originalOffset * 3]);
  91992. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  91993. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  91994. if (uvs && uvs.length) {
  91995. newUVsData.push(uvs[(originalOffset * 2)]);
  91996. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  91997. }
  91998. else if (colorsData && colorsData.length) {
  91999. newColorsData.push(colorsData[(originalOffset * 4)]);
  92000. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92001. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92002. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92003. }
  92004. ++vertexCount;
  92005. });
  92006. }
  92007. }
  92008. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92009. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92010. var submeshesArray = this._reconstructedMesh.subMeshes;
  92011. this._reconstructedMesh.subMeshes = [];
  92012. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92013. var originalIndices = this._mesh.getIndices();
  92014. for (i = 0; i < newTriangles.length; ++i) {
  92015. t = newTriangles[i]; //now get the new referencing point for each vertex
  92016. [0, 1, 2].forEach(function (idx) {
  92017. var id = originalIndices[t.originalOffset + idx];
  92018. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92019. if (offset < 0)
  92020. offset = 0;
  92021. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92022. });
  92023. }
  92024. //overwriting the old vertex buffers and indices.
  92025. this._reconstructedMesh.setIndices(newIndicesArray);
  92026. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92027. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92028. if (newUVsData.length > 0)
  92029. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92030. if (newColorsData.length > 0)
  92031. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92032. //create submesh
  92033. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92034. if (submeshIndex > 0) {
  92035. this._reconstructedMesh.subMeshes = [];
  92036. submeshesArray.forEach(function (submesh) {
  92037. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92038. });
  92039. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92040. }
  92041. };
  92042. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92043. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92044. this._reconstructedMesh.material = this._mesh.material;
  92045. this._reconstructedMesh.parent = this._mesh.parent;
  92046. this._reconstructedMesh.isVisible = false;
  92047. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92048. };
  92049. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92050. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92051. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92052. if (t.deleted)
  92053. continue;
  92054. var s = this.references[vertex1.triangleStart + i].vertexId;
  92055. var v1 = t.vertices[(s + 1) % 3];
  92056. var v2 = t.vertices[(s + 2) % 3];
  92057. if ((v1 === vertex2 || v2 === vertex2)) {
  92058. deletedArray[i] = true;
  92059. delTr.push(t);
  92060. continue;
  92061. }
  92062. var d1 = v1.position.subtract(point);
  92063. d1 = d1.normalize();
  92064. var d2 = v2.position.subtract(point);
  92065. d2 = d2.normalize();
  92066. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92067. return true;
  92068. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92069. deletedArray[i] = false;
  92070. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92071. return true;
  92072. }
  92073. return false;
  92074. };
  92075. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92076. var newDeleted = deletedTriangles;
  92077. for (var i = 0; i < vertex.triangleCount; ++i) {
  92078. var ref = this.references[vertex.triangleStart + i];
  92079. var t = this.triangles[ref.triangleId];
  92080. if (t.deleted)
  92081. continue;
  92082. if (deletedArray[i] && t.deletePending) {
  92083. t.deleted = true;
  92084. newDeleted++;
  92085. continue;
  92086. }
  92087. t.vertices[ref.vertexId] = origVertex;
  92088. t.isDirty = true;
  92089. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92090. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92091. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92092. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92093. this.references.push(ref);
  92094. }
  92095. return newDeleted;
  92096. };
  92097. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92098. for (var i = 0; i < this.vertices.length; ++i) {
  92099. var vCount = [];
  92100. var vId = [];
  92101. var v = this.vertices[i];
  92102. var j;
  92103. for (j = 0; j < v.triangleCount; ++j) {
  92104. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92105. for (var ii = 0; ii < 3; ii++) {
  92106. var ofs = 0;
  92107. var vv = triangle.vertices[ii];
  92108. while (ofs < vCount.length) {
  92109. if (vId[ofs] === vv.id)
  92110. break;
  92111. ++ofs;
  92112. }
  92113. if (ofs === vCount.length) {
  92114. vCount.push(1);
  92115. vId.push(vv.id);
  92116. }
  92117. else {
  92118. vCount[ofs]++;
  92119. }
  92120. }
  92121. }
  92122. for (j = 0; j < vCount.length; ++j) {
  92123. if (vCount[j] === 1) {
  92124. this.vertices[vId[j]].isBorder = true;
  92125. }
  92126. else {
  92127. this.vertices[vId[j]].isBorder = false;
  92128. }
  92129. }
  92130. }
  92131. };
  92132. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92133. if (identifyBorders === void 0) { identifyBorders = false; }
  92134. var i;
  92135. if (!identifyBorders) {
  92136. var newTrianglesVector = [];
  92137. for (i = 0; i < this.triangles.length; ++i) {
  92138. if (!this.triangles[i].deleted) {
  92139. newTrianglesVector.push(this.triangles[i]);
  92140. }
  92141. }
  92142. this.triangles = newTrianglesVector;
  92143. }
  92144. for (i = 0; i < this.vertices.length; ++i) {
  92145. this.vertices[i].triangleCount = 0;
  92146. this.vertices[i].triangleStart = 0;
  92147. }
  92148. var t;
  92149. var j;
  92150. var v;
  92151. for (i = 0; i < this.triangles.length; ++i) {
  92152. t = this.triangles[i];
  92153. for (j = 0; j < 3; ++j) {
  92154. v = t.vertices[j];
  92155. v.triangleCount++;
  92156. }
  92157. }
  92158. var tStart = 0;
  92159. for (i = 0; i < this.vertices.length; ++i) {
  92160. this.vertices[i].triangleStart = tStart;
  92161. tStart += this.vertices[i].triangleCount;
  92162. this.vertices[i].triangleCount = 0;
  92163. }
  92164. var newReferences = new Array(this.triangles.length * 3);
  92165. for (i = 0; i < this.triangles.length; ++i) {
  92166. t = this.triangles[i];
  92167. for (j = 0; j < 3; ++j) {
  92168. v = t.vertices[j];
  92169. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92170. v.triangleCount++;
  92171. }
  92172. }
  92173. this.references = newReferences;
  92174. if (identifyBorders) {
  92175. this.identifyBorder();
  92176. }
  92177. };
  92178. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92179. var x = point.x;
  92180. var y = point.y;
  92181. var z = point.z;
  92182. 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
  92183. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92184. };
  92185. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92186. var q = vertex1.q.add(vertex2.q);
  92187. var border = vertex1.isBorder && vertex2.isBorder;
  92188. var error = 0;
  92189. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92190. if (qDet !== 0 && !border) {
  92191. if (!pointResult) {
  92192. pointResult = BABYLON.Vector3.Zero();
  92193. }
  92194. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92195. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92196. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92197. error = this.vertexError(q, pointResult);
  92198. }
  92199. else {
  92200. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92201. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92202. var error1 = this.vertexError(q, vertex1.position);
  92203. var error2 = this.vertexError(q, vertex2.position);
  92204. var error3 = this.vertexError(q, p3);
  92205. error = Math.min(error1, error2, error3);
  92206. if (error === error1) {
  92207. if (pointResult) {
  92208. pointResult.copyFrom(vertex1.position);
  92209. }
  92210. }
  92211. else if (error === error2) {
  92212. if (pointResult) {
  92213. pointResult.copyFrom(vertex2.position);
  92214. }
  92215. }
  92216. else {
  92217. if (pointResult) {
  92218. pointResult.copyFrom(p3);
  92219. }
  92220. }
  92221. }
  92222. return error;
  92223. };
  92224. return QuadraticErrorSimplification;
  92225. }());
  92226. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92227. })(BABYLON || (BABYLON = {}));
  92228. //# sourceMappingURL=babylon.meshSimplification.js.map
  92229. var BABYLON;
  92230. (function (BABYLON) {
  92231. var MeshLODLevel = /** @class */ (function () {
  92232. function MeshLODLevel(distance, mesh) {
  92233. this.distance = distance;
  92234. this.mesh = mesh;
  92235. }
  92236. return MeshLODLevel;
  92237. }());
  92238. BABYLON.MeshLODLevel = MeshLODLevel;
  92239. })(BABYLON || (BABYLON = {}));
  92240. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92241. var BABYLON;
  92242. (function (BABYLON) {
  92243. /**
  92244. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92245. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92246. */
  92247. var SceneOptimization = /** @class */ (function () {
  92248. /**
  92249. * Creates the SceneOptimization object
  92250. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92251. * @param desc defines the description associated with the optimization
  92252. */
  92253. function SceneOptimization(
  92254. /**
  92255. * Defines the priority of this optimization (0 by default which means first in the list)
  92256. */
  92257. priority) {
  92258. if (priority === void 0) { priority = 0; }
  92259. this.priority = priority;
  92260. }
  92261. /**
  92262. * Gets a string describing the action executed by the current optimization
  92263. * @returns description string
  92264. */
  92265. SceneOptimization.prototype.getDescription = function () {
  92266. return "";
  92267. };
  92268. /**
  92269. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92270. * @param scene defines the current scene where to apply this optimization
  92271. * @param optimizer defines the current optimizer
  92272. * @returns true if everything that can be done was applied
  92273. */
  92274. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92275. return true;
  92276. };
  92277. ;
  92278. return SceneOptimization;
  92279. }());
  92280. BABYLON.SceneOptimization = SceneOptimization;
  92281. /**
  92282. * Defines an optimization used to reduce the size of render target textures
  92283. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92284. */
  92285. var TextureOptimization = /** @class */ (function (_super) {
  92286. __extends(TextureOptimization, _super);
  92287. /**
  92288. * Creates the TextureOptimization object
  92289. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92290. * @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
  92291. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92292. */
  92293. function TextureOptimization(
  92294. /**
  92295. * Defines the priority of this optimization (0 by default which means first in the list)
  92296. */
  92297. priority,
  92298. /**
  92299. * 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
  92300. */
  92301. maximumSize,
  92302. /**
  92303. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92304. */
  92305. step) {
  92306. if (priority === void 0) { priority = 0; }
  92307. if (maximumSize === void 0) { maximumSize = 1024; }
  92308. if (step === void 0) { step = 0.5; }
  92309. var _this = _super.call(this, priority) || this;
  92310. _this.priority = priority;
  92311. _this.maximumSize = maximumSize;
  92312. _this.step = step;
  92313. return _this;
  92314. }
  92315. /**
  92316. * Gets a string describing the action executed by the current optimization
  92317. * @returns description string
  92318. */
  92319. TextureOptimization.prototype.getDescription = function () {
  92320. return "Reducing render target texture size to " + this.maximumSize;
  92321. };
  92322. /**
  92323. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92324. * @param scene defines the current scene where to apply this optimization
  92325. * @param optimizer defines the current optimizer
  92326. * @returns true if everything that can be done was applied
  92327. */
  92328. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92329. var allDone = true;
  92330. for (var index = 0; index < scene.textures.length; index++) {
  92331. var texture = scene.textures[index];
  92332. if (!texture.canRescale || texture.getContext) {
  92333. continue;
  92334. }
  92335. var currentSize = texture.getSize();
  92336. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92337. if (maxDimension > this.maximumSize) {
  92338. texture.scale(this.step);
  92339. allDone = false;
  92340. }
  92341. }
  92342. return allDone;
  92343. };
  92344. return TextureOptimization;
  92345. }(SceneOptimization));
  92346. BABYLON.TextureOptimization = TextureOptimization;
  92347. /**
  92348. * Defines an optimization used to increase or decrease the rendering resolution
  92349. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92350. */
  92351. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92352. __extends(HardwareScalingOptimization, _super);
  92353. /**
  92354. * Creates the HardwareScalingOptimization object
  92355. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92356. * @param maximumScale defines the maximum scale to use (2 by default)
  92357. * @param step defines the step to use between two passes (0.5 by default)
  92358. */
  92359. function HardwareScalingOptimization(
  92360. /**
  92361. * Defines the priority of this optimization (0 by default which means first in the list)
  92362. */
  92363. priority,
  92364. /**
  92365. * Defines the maximum scale to use (2 by default)
  92366. */
  92367. maximumScale,
  92368. /**
  92369. * Defines the step to use between two passes (0.5 by default)
  92370. */
  92371. step) {
  92372. if (priority === void 0) { priority = 0; }
  92373. if (maximumScale === void 0) { maximumScale = 2; }
  92374. if (step === void 0) { step = 0.25; }
  92375. var _this = _super.call(this, priority) || this;
  92376. _this.priority = priority;
  92377. _this.maximumScale = maximumScale;
  92378. _this.step = step;
  92379. _this._currentScale = -1;
  92380. _this._directionOffset = 1;
  92381. return _this;
  92382. }
  92383. /**
  92384. * Gets a string describing the action executed by the current optimization
  92385. * @return description string
  92386. */
  92387. HardwareScalingOptimization.prototype.getDescription = function () {
  92388. return "Setting hardware scaling level to " + this._currentScale;
  92389. };
  92390. /**
  92391. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92392. * @param scene defines the current scene where to apply this optimization
  92393. * @param optimizer defines the current optimizer
  92394. * @returns true if everything that can be done was applied
  92395. */
  92396. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92397. if (this._currentScale === -1) {
  92398. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92399. if (this._currentScale > this.maximumScale) {
  92400. this._directionOffset = -1;
  92401. }
  92402. }
  92403. this._currentScale += this._directionOffset * this.step;
  92404. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92405. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92406. };
  92407. ;
  92408. return HardwareScalingOptimization;
  92409. }(SceneOptimization));
  92410. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92411. /**
  92412. * Defines an optimization used to remove shadows
  92413. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92414. */
  92415. var ShadowsOptimization = /** @class */ (function (_super) {
  92416. __extends(ShadowsOptimization, _super);
  92417. function ShadowsOptimization() {
  92418. return _super !== null && _super.apply(this, arguments) || this;
  92419. }
  92420. /**
  92421. * Gets a string describing the action executed by the current optimization
  92422. * @return description string
  92423. */
  92424. ShadowsOptimization.prototype.getDescription = function () {
  92425. return "Turning shadows on/off";
  92426. };
  92427. /**
  92428. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92429. * @param scene defines the current scene where to apply this optimization
  92430. * @param optimizer defines the current optimizer
  92431. * @returns true if everything that can be done was applied
  92432. */
  92433. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92434. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92435. return true;
  92436. };
  92437. ;
  92438. return ShadowsOptimization;
  92439. }(SceneOptimization));
  92440. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92441. /**
  92442. * Defines an optimization used to turn post-processes off
  92443. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92444. */
  92445. var PostProcessesOptimization = /** @class */ (function (_super) {
  92446. __extends(PostProcessesOptimization, _super);
  92447. function PostProcessesOptimization() {
  92448. return _super !== null && _super.apply(this, arguments) || this;
  92449. }
  92450. /**
  92451. * Gets a string describing the action executed by the current optimization
  92452. * @return description string
  92453. */
  92454. PostProcessesOptimization.prototype.getDescription = function () {
  92455. return "Turning post-processes on/off";
  92456. };
  92457. /**
  92458. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92459. * @param scene defines the current scene where to apply this optimization
  92460. * @param optimizer defines the current optimizer
  92461. * @returns true if everything that can be done was applied
  92462. */
  92463. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92464. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92465. return true;
  92466. };
  92467. ;
  92468. return PostProcessesOptimization;
  92469. }(SceneOptimization));
  92470. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92471. /**
  92472. * Defines an optimization used to turn lens flares off
  92473. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92474. */
  92475. var LensFlaresOptimization = /** @class */ (function (_super) {
  92476. __extends(LensFlaresOptimization, _super);
  92477. function LensFlaresOptimization() {
  92478. return _super !== null && _super.apply(this, arguments) || this;
  92479. }
  92480. /**
  92481. * Gets a string describing the action executed by the current optimization
  92482. * @return description string
  92483. */
  92484. LensFlaresOptimization.prototype.getDescription = function () {
  92485. return "Turning lens flares on/off";
  92486. };
  92487. /**
  92488. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92489. * @param scene defines the current scene where to apply this optimization
  92490. * @param optimizer defines the current optimizer
  92491. * @returns true if everything that can be done was applied
  92492. */
  92493. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92494. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92495. return true;
  92496. };
  92497. ;
  92498. return LensFlaresOptimization;
  92499. }(SceneOptimization));
  92500. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92501. /**
  92502. * Defines an optimization based on user defined callback.
  92503. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92504. */
  92505. var CustomOptimization = /** @class */ (function (_super) {
  92506. __extends(CustomOptimization, _super);
  92507. function CustomOptimization() {
  92508. return _super !== null && _super.apply(this, arguments) || this;
  92509. }
  92510. /**
  92511. * Gets a string describing the action executed by the current optimization
  92512. * @returns description string
  92513. */
  92514. CustomOptimization.prototype.getDescription = function () {
  92515. if (this.onGetDescription) {
  92516. return this.onGetDescription();
  92517. }
  92518. return "Running user defined callback";
  92519. };
  92520. /**
  92521. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92522. * @param scene defines the current scene where to apply this optimization
  92523. * @param optimizer defines the current optimizer
  92524. * @returns true if everything that can be done was applied
  92525. */
  92526. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92527. if (this.onApply) {
  92528. return this.onApply(scene, optimizer);
  92529. }
  92530. return true;
  92531. };
  92532. ;
  92533. return CustomOptimization;
  92534. }(SceneOptimization));
  92535. BABYLON.CustomOptimization = CustomOptimization;
  92536. /**
  92537. * Defines an optimization used to turn particles off
  92538. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92539. */
  92540. var ParticlesOptimization = /** @class */ (function (_super) {
  92541. __extends(ParticlesOptimization, _super);
  92542. function ParticlesOptimization() {
  92543. return _super !== null && _super.apply(this, arguments) || this;
  92544. }
  92545. /**
  92546. * Gets a string describing the action executed by the current optimization
  92547. * @return description string
  92548. */
  92549. ParticlesOptimization.prototype.getDescription = function () {
  92550. return "Turning particles on/off";
  92551. };
  92552. /**
  92553. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92554. * @param scene defines the current scene where to apply this optimization
  92555. * @param optimizer defines the current optimizer
  92556. * @returns true if everything that can be done was applied
  92557. */
  92558. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92559. scene.particlesEnabled = optimizer.isInImprovementMode;
  92560. return true;
  92561. };
  92562. ;
  92563. return ParticlesOptimization;
  92564. }(SceneOptimization));
  92565. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92566. /**
  92567. * Defines an optimization used to turn render targets off
  92568. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92569. */
  92570. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92571. __extends(RenderTargetsOptimization, _super);
  92572. function RenderTargetsOptimization() {
  92573. return _super !== null && _super.apply(this, arguments) || this;
  92574. }
  92575. /**
  92576. * Gets a string describing the action executed by the current optimization
  92577. * @return description string
  92578. */
  92579. RenderTargetsOptimization.prototype.getDescription = function () {
  92580. return "Turning render targets off";
  92581. };
  92582. /**
  92583. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92584. * @param scene defines the current scene where to apply this optimization
  92585. * @param optimizer defines the current optimizer
  92586. * @returns true if everything that can be done was applied
  92587. */
  92588. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92589. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92590. return true;
  92591. };
  92592. ;
  92593. return RenderTargetsOptimization;
  92594. }(SceneOptimization));
  92595. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92596. /**
  92597. * Defines an optimization used to merge meshes with compatible materials
  92598. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92599. */
  92600. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92601. __extends(MergeMeshesOptimization, _super);
  92602. function MergeMeshesOptimization() {
  92603. var _this = _super !== null && _super.apply(this, arguments) || this;
  92604. _this._canBeMerged = function (abstractMesh) {
  92605. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92606. return false;
  92607. }
  92608. var mesh = abstractMesh;
  92609. if (!mesh.isVisible || !mesh.isEnabled()) {
  92610. return false;
  92611. }
  92612. if (mesh.instances.length > 0) {
  92613. return false;
  92614. }
  92615. if (mesh.skeleton || mesh.hasLODLevels) {
  92616. return false;
  92617. }
  92618. if (mesh.parent) {
  92619. return false;
  92620. }
  92621. return true;
  92622. };
  92623. return _this;
  92624. }
  92625. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  92626. /**
  92627. * Gets or sets a boolean which defines if optimization octree has to be updated
  92628. */
  92629. get: function () {
  92630. return MergeMeshesOptimization._UpdateSelectionTree;
  92631. },
  92632. /**
  92633. * Gets or sets a boolean which defines if optimization octree has to be updated
  92634. */
  92635. set: function (value) {
  92636. MergeMeshesOptimization._UpdateSelectionTree = value;
  92637. },
  92638. enumerable: true,
  92639. configurable: true
  92640. });
  92641. /**
  92642. * Gets a string describing the action executed by the current optimization
  92643. * @return description string
  92644. */
  92645. MergeMeshesOptimization.prototype.getDescription = function () {
  92646. return "Merging similar meshes together";
  92647. };
  92648. /**
  92649. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92650. * @param scene defines the current scene where to apply this optimization
  92651. * @param optimizer defines the current optimizer
  92652. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  92653. * @returns true if everything that can be done was applied
  92654. */
  92655. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  92656. var globalPool = scene.meshes.slice(0);
  92657. var globalLength = globalPool.length;
  92658. for (var index = 0; index < globalLength; index++) {
  92659. var currentPool = new Array();
  92660. var current = globalPool[index];
  92661. // Checks
  92662. if (!this._canBeMerged(current)) {
  92663. continue;
  92664. }
  92665. currentPool.push(current);
  92666. // Find compatible meshes
  92667. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  92668. var otherMesh = globalPool[subIndex];
  92669. if (!this._canBeMerged(otherMesh)) {
  92670. continue;
  92671. }
  92672. if (otherMesh.material !== current.material) {
  92673. continue;
  92674. }
  92675. if (otherMesh.checkCollisions !== current.checkCollisions) {
  92676. continue;
  92677. }
  92678. currentPool.push(otherMesh);
  92679. globalLength--;
  92680. globalPool.splice(subIndex, 1);
  92681. subIndex--;
  92682. }
  92683. if (currentPool.length < 2) {
  92684. continue;
  92685. }
  92686. // Merge meshes
  92687. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  92688. }
  92689. if (updateSelectionTree != undefined) {
  92690. if (updateSelectionTree) {
  92691. scene.createOrUpdateSelectionOctree();
  92692. }
  92693. }
  92694. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  92695. scene.createOrUpdateSelectionOctree();
  92696. }
  92697. return true;
  92698. };
  92699. ;
  92700. MergeMeshesOptimization._UpdateSelectionTree = false;
  92701. return MergeMeshesOptimization;
  92702. }(SceneOptimization));
  92703. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  92704. /**
  92705. * Defines a list of options used by SceneOptimizer
  92706. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92707. */
  92708. var SceneOptimizerOptions = /** @class */ (function () {
  92709. /**
  92710. * Creates a new list of options used by SceneOptimizer
  92711. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  92712. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  92713. */
  92714. function SceneOptimizerOptions(
  92715. /**
  92716. * Defines the target frame rate to reach (60 by default)
  92717. */
  92718. targetFrameRate,
  92719. /**
  92720. * Defines the interval between two checkes (2000ms by default)
  92721. */
  92722. trackerDuration) {
  92723. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  92724. if (trackerDuration === void 0) { trackerDuration = 2000; }
  92725. this.targetFrameRate = targetFrameRate;
  92726. this.trackerDuration = trackerDuration;
  92727. /**
  92728. * Gets the list of optimizations to apply
  92729. */
  92730. this.optimizations = new Array();
  92731. }
  92732. /**
  92733. * Add a new optimization
  92734. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  92735. * @returns the current SceneOptimizerOptions
  92736. */
  92737. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  92738. this.optimizations.push(optimization);
  92739. return this;
  92740. };
  92741. /**
  92742. * Add a new custom optimization
  92743. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  92744. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  92745. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92746. * @returns the current SceneOptimizerOptions
  92747. */
  92748. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  92749. if (priority === void 0) { priority = 0; }
  92750. var optimization = new CustomOptimization(priority);
  92751. optimization.onApply = onApply;
  92752. optimization.onGetDescription = onGetDescription;
  92753. this.optimizations.push(optimization);
  92754. return this;
  92755. };
  92756. /**
  92757. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  92758. * @param targetFrameRate defines the target frame rate (60 by default)
  92759. * @returns a SceneOptimizerOptions object
  92760. */
  92761. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  92762. var result = new SceneOptimizerOptions(targetFrameRate);
  92763. var priority = 0;
  92764. result.addOptimization(new MergeMeshesOptimization(priority));
  92765. result.addOptimization(new ShadowsOptimization(priority));
  92766. result.addOptimization(new LensFlaresOptimization(priority));
  92767. // Next priority
  92768. priority++;
  92769. result.addOptimization(new PostProcessesOptimization(priority));
  92770. result.addOptimization(new ParticlesOptimization(priority));
  92771. // Next priority
  92772. priority++;
  92773. result.addOptimization(new TextureOptimization(priority, 1024));
  92774. return result;
  92775. };
  92776. /**
  92777. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  92778. * @param targetFrameRate defines the target frame rate (60 by default)
  92779. * @returns a SceneOptimizerOptions object
  92780. */
  92781. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  92782. var result = new SceneOptimizerOptions(targetFrameRate);
  92783. var priority = 0;
  92784. result.addOptimization(new MergeMeshesOptimization(priority));
  92785. result.addOptimization(new ShadowsOptimization(priority));
  92786. result.addOptimization(new LensFlaresOptimization(priority));
  92787. // Next priority
  92788. priority++;
  92789. result.addOptimization(new PostProcessesOptimization(priority));
  92790. result.addOptimization(new ParticlesOptimization(priority));
  92791. // Next priority
  92792. priority++;
  92793. result.addOptimization(new TextureOptimization(priority, 512));
  92794. // Next priority
  92795. priority++;
  92796. result.addOptimization(new RenderTargetsOptimization(priority));
  92797. // Next priority
  92798. priority++;
  92799. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  92800. return result;
  92801. };
  92802. /**
  92803. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  92804. * @param targetFrameRate defines the target frame rate (60 by default)
  92805. * @returns a SceneOptimizerOptions object
  92806. */
  92807. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  92808. var result = new SceneOptimizerOptions(targetFrameRate);
  92809. var priority = 0;
  92810. result.addOptimization(new MergeMeshesOptimization(priority));
  92811. result.addOptimization(new ShadowsOptimization(priority));
  92812. result.addOptimization(new LensFlaresOptimization(priority));
  92813. // Next priority
  92814. priority++;
  92815. result.addOptimization(new PostProcessesOptimization(priority));
  92816. result.addOptimization(new ParticlesOptimization(priority));
  92817. // Next priority
  92818. priority++;
  92819. result.addOptimization(new TextureOptimization(priority, 256));
  92820. // Next priority
  92821. priority++;
  92822. result.addOptimization(new RenderTargetsOptimization(priority));
  92823. // Next priority
  92824. priority++;
  92825. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  92826. return result;
  92827. };
  92828. return SceneOptimizerOptions;
  92829. }());
  92830. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  92831. /**
  92832. * Class used to run optimizations in order to reach a target frame rate
  92833. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92834. */
  92835. var SceneOptimizer = /** @class */ (function () {
  92836. /**
  92837. * Creates a new SceneOptimizer
  92838. * @param scene defines the scene to work on
  92839. * @param options defines the options to use with the SceneOptimizer
  92840. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  92841. * @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)
  92842. */
  92843. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  92844. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  92845. if (improvementMode === void 0) { improvementMode = false; }
  92846. var _this = this;
  92847. this._isRunning = false;
  92848. this._currentPriorityLevel = 0;
  92849. this._targetFrameRate = 60;
  92850. this._trackerDuration = 2000;
  92851. this._currentFrameRate = 0;
  92852. this._improvementMode = false;
  92853. /**
  92854. * Defines an observable called when the optimizer reaches the target frame rate
  92855. */
  92856. this.onSuccessObservable = new BABYLON.Observable();
  92857. /**
  92858. * Defines an observable called when the optimizer enables an optimization
  92859. */
  92860. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  92861. /**
  92862. * Defines an observable called when the optimizer is not able to reach the target frame rate
  92863. */
  92864. this.onFailureObservable = new BABYLON.Observable();
  92865. if (!options) {
  92866. this._options = new SceneOptimizerOptions();
  92867. }
  92868. else {
  92869. this._options = options;
  92870. }
  92871. if (this._options.targetFrameRate) {
  92872. this._targetFrameRate = this._options.targetFrameRate;
  92873. }
  92874. if (this._options.trackerDuration) {
  92875. this._trackerDuration = this._options.trackerDuration;
  92876. }
  92877. if (autoGeneratePriorities) {
  92878. var priority = 0;
  92879. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  92880. var optim = _a[_i];
  92881. optim.priority = priority++;
  92882. }
  92883. }
  92884. this._improvementMode = improvementMode;
  92885. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92886. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  92887. _this._sceneDisposeObserver = null;
  92888. _this.dispose();
  92889. });
  92890. }
  92891. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  92892. /**
  92893. * Gets a boolean indicating if the optimizer is in improvement mode
  92894. */
  92895. get: function () {
  92896. return this._improvementMode;
  92897. },
  92898. enumerable: true,
  92899. configurable: true
  92900. });
  92901. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  92902. /**
  92903. * Gets the current priority level (0 at start)
  92904. */
  92905. get: function () {
  92906. return this._currentPriorityLevel;
  92907. },
  92908. enumerable: true,
  92909. configurable: true
  92910. });
  92911. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  92912. /**
  92913. * Gets the current frame rate checked by the SceneOptimizer
  92914. */
  92915. get: function () {
  92916. return this._currentFrameRate;
  92917. },
  92918. enumerable: true,
  92919. configurable: true
  92920. });
  92921. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  92922. /**
  92923. * Gets or sets the current target frame rate (60 by default)
  92924. */
  92925. get: function () {
  92926. return this._targetFrameRate;
  92927. },
  92928. /**
  92929. * Gets or sets the current target frame rate (60 by default)
  92930. */
  92931. set: function (value) {
  92932. this._targetFrameRate = value;
  92933. },
  92934. enumerable: true,
  92935. configurable: true
  92936. });
  92937. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  92938. /**
  92939. * Gets or sets the current interval between two checks (every 2000ms by default)
  92940. */
  92941. get: function () {
  92942. return this._trackerDuration;
  92943. },
  92944. /**
  92945. * Gets or sets the current interval between two checks (every 2000ms by default)
  92946. */
  92947. set: function (value) {
  92948. this._trackerDuration = value;
  92949. },
  92950. enumerable: true,
  92951. configurable: true
  92952. });
  92953. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  92954. /**
  92955. * Gets the list of active optimizations
  92956. */
  92957. get: function () {
  92958. return this._options.optimizations;
  92959. },
  92960. enumerable: true,
  92961. configurable: true
  92962. });
  92963. /**
  92964. * Stops the current optimizer
  92965. */
  92966. SceneOptimizer.prototype.stop = function () {
  92967. this._isRunning = false;
  92968. };
  92969. /**
  92970. * Reset the optimizer to initial step (current priority level = 0)
  92971. */
  92972. SceneOptimizer.prototype.reset = function () {
  92973. this._currentPriorityLevel = 0;
  92974. };
  92975. /**
  92976. * Start the optimizer. By default it will try to reach a specific framerate
  92977. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  92978. */
  92979. SceneOptimizer.prototype.start = function () {
  92980. var _this = this;
  92981. if (this._isRunning) {
  92982. return;
  92983. }
  92984. this._isRunning = true;
  92985. // Let's wait for the scene to be ready before running our check
  92986. this._scene.executeWhenReady(function () {
  92987. setTimeout(function () {
  92988. _this._checkCurrentState();
  92989. }, _this._trackerDuration);
  92990. });
  92991. };
  92992. SceneOptimizer.prototype._checkCurrentState = function () {
  92993. var _this = this;
  92994. if (!this._isRunning) {
  92995. return;
  92996. }
  92997. var scene = this._scene;
  92998. var options = this._options;
  92999. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93000. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93001. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93002. this._isRunning = false;
  93003. this.onSuccessObservable.notifyObservers(this);
  93004. return;
  93005. }
  93006. // Apply current level of optimizations
  93007. var allDone = true;
  93008. var noOptimizationApplied = true;
  93009. for (var index = 0; index < options.optimizations.length; index++) {
  93010. var optimization = options.optimizations[index];
  93011. if (optimization.priority === this._currentPriorityLevel) {
  93012. noOptimizationApplied = false;
  93013. allDone = allDone && optimization.apply(scene, this);
  93014. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93015. }
  93016. }
  93017. // If no optimization was applied, this is a failure :(
  93018. if (noOptimizationApplied) {
  93019. this._isRunning = false;
  93020. this.onFailureObservable.notifyObservers(this);
  93021. return;
  93022. }
  93023. // If all optimizations were done, move to next level
  93024. if (allDone) {
  93025. this._currentPriorityLevel++;
  93026. }
  93027. // Let's the system running for a specific amount of time before checking FPS
  93028. scene.executeWhenReady(function () {
  93029. setTimeout(function () {
  93030. _this._checkCurrentState();
  93031. }, _this._trackerDuration);
  93032. });
  93033. };
  93034. /**
  93035. * Release all resources
  93036. */
  93037. SceneOptimizer.prototype.dispose = function () {
  93038. this.stop();
  93039. this.onSuccessObservable.clear();
  93040. this.onFailureObservable.clear();
  93041. this.onNewOptimizationAppliedObservable.clear();
  93042. if (this._sceneDisposeObserver) {
  93043. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93044. }
  93045. };
  93046. /**
  93047. * Helper function to create a SceneOptimizer with one single line of code
  93048. * @param scene defines the scene to work on
  93049. * @param options defines the options to use with the SceneOptimizer
  93050. * @param onSuccess defines a callback to call on success
  93051. * @param onFailure defines a callback to call on failure
  93052. * @returns the new SceneOptimizer object
  93053. */
  93054. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93055. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93056. if (onSuccess) {
  93057. optimizer.onSuccessObservable.add(function () {
  93058. onSuccess();
  93059. });
  93060. }
  93061. if (onFailure) {
  93062. optimizer.onFailureObservable.add(function () {
  93063. onFailure();
  93064. });
  93065. }
  93066. optimizer.start();
  93067. return optimizer;
  93068. };
  93069. return SceneOptimizer;
  93070. }());
  93071. BABYLON.SceneOptimizer = SceneOptimizer;
  93072. })(BABYLON || (BABYLON = {}));
  93073. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93074. var BABYLON;
  93075. (function (BABYLON) {
  93076. var OutlineRenderer = /** @class */ (function () {
  93077. function OutlineRenderer(scene) {
  93078. this.zOffset = 1;
  93079. this._scene = scene;
  93080. }
  93081. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93082. var _this = this;
  93083. if (useOverlay === void 0) { useOverlay = false; }
  93084. var scene = this._scene;
  93085. var engine = this._scene.getEngine();
  93086. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93087. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93088. return;
  93089. }
  93090. var mesh = subMesh.getRenderingMesh();
  93091. var material = subMesh.getMaterial();
  93092. if (!material || !scene.activeCamera) {
  93093. return;
  93094. }
  93095. engine.enableEffect(this._effect);
  93096. // Logarithmic depth
  93097. if (material.useLogarithmicDepth) {
  93098. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93099. }
  93100. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93101. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93102. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93103. // Bones
  93104. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93105. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93106. }
  93107. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93108. // Alpha test
  93109. if (material && material.needAlphaTesting()) {
  93110. var alphaTexture = material.getAlphaTestTexture();
  93111. if (alphaTexture) {
  93112. this._effect.setTexture("diffuseSampler", alphaTexture);
  93113. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93114. }
  93115. }
  93116. engine.setZOffset(-this.zOffset);
  93117. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93118. engine.setZOffset(0);
  93119. };
  93120. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93121. var defines = [];
  93122. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93123. var mesh = subMesh.getMesh();
  93124. var material = subMesh.getMaterial();
  93125. if (material) {
  93126. // Alpha test
  93127. if (material.needAlphaTesting()) {
  93128. defines.push("#define ALPHATEST");
  93129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93130. attribs.push(BABYLON.VertexBuffer.UVKind);
  93131. defines.push("#define UV1");
  93132. }
  93133. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93134. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93135. defines.push("#define UV2");
  93136. }
  93137. }
  93138. //Logarithmic depth
  93139. if (material.useLogarithmicDepth) {
  93140. defines.push("#define LOGARITHMICDEPTH");
  93141. }
  93142. }
  93143. // Bones
  93144. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93145. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93146. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93147. if (mesh.numBoneInfluencers > 4) {
  93148. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93149. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93150. }
  93151. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93152. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93153. }
  93154. else {
  93155. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93156. }
  93157. // Instances
  93158. if (useInstances) {
  93159. defines.push("#define INSTANCES");
  93160. attribs.push("world0");
  93161. attribs.push("world1");
  93162. attribs.push("world2");
  93163. attribs.push("world3");
  93164. }
  93165. // Get correct effect
  93166. var join = defines.join("\n");
  93167. if (this._cachedDefines !== join) {
  93168. this._cachedDefines = join;
  93169. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93170. }
  93171. return this._effect.isReady();
  93172. };
  93173. return OutlineRenderer;
  93174. }());
  93175. BABYLON.OutlineRenderer = OutlineRenderer;
  93176. })(BABYLON || (BABYLON = {}));
  93177. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93178. var BABYLON;
  93179. (function (BABYLON) {
  93180. var FaceAdjacencies = /** @class */ (function () {
  93181. function FaceAdjacencies() {
  93182. this.edges = new Array();
  93183. this.edgesConnectedCount = 0;
  93184. }
  93185. return FaceAdjacencies;
  93186. }());
  93187. var EdgesRenderer = /** @class */ (function () {
  93188. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93189. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93190. if (epsilon === void 0) { epsilon = 0.95; }
  93191. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93192. this.edgesWidthScalerForOrthographic = 1000.0;
  93193. this.edgesWidthScalerForPerspective = 50.0;
  93194. this._linesPositions = new Array();
  93195. this._linesNormals = new Array();
  93196. this._linesIndices = new Array();
  93197. this._buffers = {};
  93198. this._checkVerticesInsteadOfIndices = false;
  93199. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93200. this.isEnabled = true;
  93201. this._source = source;
  93202. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93203. this._epsilon = epsilon;
  93204. this._prepareRessources();
  93205. this._generateEdgesLines();
  93206. }
  93207. EdgesRenderer.prototype._prepareRessources = function () {
  93208. if (this._lineShader) {
  93209. return;
  93210. }
  93211. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93212. attributes: ["position", "normal"],
  93213. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93214. });
  93215. this._lineShader.disableDepthWrite = true;
  93216. this._lineShader.backFaceCulling = false;
  93217. };
  93218. EdgesRenderer.prototype._rebuild = function () {
  93219. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93220. if (buffer) {
  93221. buffer._rebuild();
  93222. }
  93223. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93224. if (buffer) {
  93225. buffer._rebuild();
  93226. }
  93227. var scene = this._source.getScene();
  93228. var engine = scene.getEngine();
  93229. this._ib = engine.createIndexBuffer(this._linesIndices);
  93230. };
  93231. EdgesRenderer.prototype.dispose = function () {
  93232. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93233. if (buffer) {
  93234. buffer.dispose();
  93235. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93236. }
  93237. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93238. if (buffer) {
  93239. buffer.dispose();
  93240. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93241. }
  93242. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93243. this._lineShader.dispose();
  93244. };
  93245. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93246. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93247. return 0;
  93248. }
  93249. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93250. return 1;
  93251. }
  93252. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93253. return 2;
  93254. }
  93255. return -1;
  93256. };
  93257. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93258. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93259. return 0;
  93260. }
  93261. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93262. return 1;
  93263. }
  93264. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93265. return 2;
  93266. }
  93267. return -1;
  93268. };
  93269. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93270. var needToCreateLine;
  93271. if (edge === undefined) {
  93272. needToCreateLine = true;
  93273. }
  93274. else {
  93275. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93276. needToCreateLine = dotProduct < this._epsilon;
  93277. }
  93278. if (needToCreateLine) {
  93279. var offset = this._linesPositions.length / 3;
  93280. var normal = p0.subtract(p1);
  93281. normal.normalize();
  93282. // Positions
  93283. this._linesPositions.push(p0.x);
  93284. this._linesPositions.push(p0.y);
  93285. this._linesPositions.push(p0.z);
  93286. this._linesPositions.push(p0.x);
  93287. this._linesPositions.push(p0.y);
  93288. this._linesPositions.push(p0.z);
  93289. this._linesPositions.push(p1.x);
  93290. this._linesPositions.push(p1.y);
  93291. this._linesPositions.push(p1.z);
  93292. this._linesPositions.push(p1.x);
  93293. this._linesPositions.push(p1.y);
  93294. this._linesPositions.push(p1.z);
  93295. // Normals
  93296. this._linesNormals.push(p1.x);
  93297. this._linesNormals.push(p1.y);
  93298. this._linesNormals.push(p1.z);
  93299. this._linesNormals.push(-1);
  93300. this._linesNormals.push(p1.x);
  93301. this._linesNormals.push(p1.y);
  93302. this._linesNormals.push(p1.z);
  93303. this._linesNormals.push(1);
  93304. this._linesNormals.push(p0.x);
  93305. this._linesNormals.push(p0.y);
  93306. this._linesNormals.push(p0.z);
  93307. this._linesNormals.push(-1);
  93308. this._linesNormals.push(p0.x);
  93309. this._linesNormals.push(p0.y);
  93310. this._linesNormals.push(p0.z);
  93311. this._linesNormals.push(1);
  93312. // Indices
  93313. this._linesIndices.push(offset);
  93314. this._linesIndices.push(offset + 1);
  93315. this._linesIndices.push(offset + 2);
  93316. this._linesIndices.push(offset);
  93317. this._linesIndices.push(offset + 2);
  93318. this._linesIndices.push(offset + 3);
  93319. }
  93320. };
  93321. EdgesRenderer.prototype._generateEdgesLines = function () {
  93322. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93323. var indices = this._source.getIndices();
  93324. if (!indices || !positions) {
  93325. return;
  93326. }
  93327. // First let's find adjacencies
  93328. var adjacencies = new Array();
  93329. var faceNormals = new Array();
  93330. var index;
  93331. var faceAdjacencies;
  93332. // Prepare faces
  93333. for (index = 0; index < indices.length; index += 3) {
  93334. faceAdjacencies = new FaceAdjacencies();
  93335. var p0Index = indices[index];
  93336. var p1Index = indices[index + 1];
  93337. var p2Index = indices[index + 2];
  93338. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93339. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93340. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93341. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93342. faceNormal.normalize();
  93343. faceNormals.push(faceNormal);
  93344. adjacencies.push(faceAdjacencies);
  93345. }
  93346. // Scan
  93347. for (index = 0; index < adjacencies.length; index++) {
  93348. faceAdjacencies = adjacencies[index];
  93349. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93350. var otherFaceAdjacencies = adjacencies[otherIndex];
  93351. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93352. break;
  93353. }
  93354. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93355. continue;
  93356. }
  93357. var otherP0 = indices[otherIndex * 3];
  93358. var otherP1 = indices[otherIndex * 3 + 1];
  93359. var otherP2 = indices[otherIndex * 3 + 2];
  93360. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93361. var otherEdgeIndex = 0;
  93362. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93363. continue;
  93364. }
  93365. switch (edgeIndex) {
  93366. case 0:
  93367. if (this._checkVerticesInsteadOfIndices) {
  93368. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93369. }
  93370. else {
  93371. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93372. }
  93373. break;
  93374. case 1:
  93375. if (this._checkVerticesInsteadOfIndices) {
  93376. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93377. }
  93378. else {
  93379. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93380. }
  93381. break;
  93382. case 2:
  93383. if (this._checkVerticesInsteadOfIndices) {
  93384. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93385. }
  93386. else {
  93387. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93388. }
  93389. break;
  93390. }
  93391. if (otherEdgeIndex === -1) {
  93392. continue;
  93393. }
  93394. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93395. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93396. faceAdjacencies.edgesConnectedCount++;
  93397. otherFaceAdjacencies.edgesConnectedCount++;
  93398. if (faceAdjacencies.edgesConnectedCount === 3) {
  93399. break;
  93400. }
  93401. }
  93402. }
  93403. }
  93404. // Create lines
  93405. for (index = 0; index < adjacencies.length; index++) {
  93406. // 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
  93407. var current = adjacencies[index];
  93408. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93409. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93410. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93411. }
  93412. // Merge into a single mesh
  93413. var engine = this._source.getScene().getEngine();
  93414. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93415. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93416. this._ib = engine.createIndexBuffer(this._linesIndices);
  93417. this._indicesCount = this._linesIndices.length;
  93418. };
  93419. EdgesRenderer.prototype.render = function () {
  93420. var scene = this._source.getScene();
  93421. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93422. return;
  93423. }
  93424. var engine = scene.getEngine();
  93425. this._lineShader._preBind();
  93426. // VBOs
  93427. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93428. scene.resetCachedMaterial();
  93429. this._lineShader.setColor4("color", this._source.edgesColor);
  93430. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93431. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93432. }
  93433. else {
  93434. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93435. }
  93436. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93437. this._lineShader.bind(this._source.getWorldMatrix());
  93438. // Draw order
  93439. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93440. this._lineShader.unbind();
  93441. engine.setDepthWrite(true);
  93442. };
  93443. return EdgesRenderer;
  93444. }());
  93445. BABYLON.EdgesRenderer = EdgesRenderer;
  93446. })(BABYLON || (BABYLON = {}));
  93447. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93448. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93449. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93450. s = arguments[i];
  93451. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93452. t[p] = s[p];
  93453. }
  93454. return t;
  93455. };
  93456. var BABYLON;
  93457. (function (BABYLON) {
  93458. /**
  93459. * The effect layer Helps adding post process effect blended with the main pass.
  93460. *
  93461. * This can be for instance use to generate glow or higlight effects on the scene.
  93462. *
  93463. * The effect layer class can not be used directly and is intented to inherited from to be
  93464. * customized per effects.
  93465. */
  93466. var EffectLayer = /** @class */ (function () {
  93467. /**
  93468. * Instantiates a new effect Layer and references it in the scene.
  93469. * @param name The name of the layer
  93470. * @param scene The scene to use the layer in
  93471. */
  93472. function EffectLayer(
  93473. /** The Friendly of the effect in the scene */
  93474. name, scene) {
  93475. this._vertexBuffers = {};
  93476. this._maxSize = 0;
  93477. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93478. this._shouldRender = true;
  93479. this._postProcesses = [];
  93480. this._textures = [];
  93481. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93482. /**
  93483. * The clear color of the texture used to generate the glow map.
  93484. */
  93485. this.neutralColor = new BABYLON.Color4();
  93486. /**
  93487. * Specifies wether the highlight layer is enabled or not.
  93488. */
  93489. this.isEnabled = true;
  93490. /**
  93491. * An event triggered when the effect layer has been disposed.
  93492. */
  93493. this.onDisposeObservable = new BABYLON.Observable();
  93494. /**
  93495. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93496. */
  93497. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93498. /**
  93499. * An event triggered when the generated texture is being merged in the scene.
  93500. */
  93501. this.onBeforeComposeObservable = new BABYLON.Observable();
  93502. /**
  93503. * An event triggered when the generated texture has been merged in the scene.
  93504. */
  93505. this.onAfterComposeObservable = new BABYLON.Observable();
  93506. /**
  93507. * An event triggered when the efffect layer changes its size.
  93508. */
  93509. this.onSizeChangedObservable = new BABYLON.Observable();
  93510. this.name = name;
  93511. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93512. this._engine = scene.getEngine();
  93513. this._maxSize = this._engine.getCaps().maxTextureSize;
  93514. this._scene.effectLayers.push(this);
  93515. // Generate Buffers
  93516. this._generateIndexBuffer();
  93517. this._genrateVertexBuffer();
  93518. }
  93519. Object.defineProperty(EffectLayer.prototype, "camera", {
  93520. /**
  93521. * Gets the camera attached to the layer.
  93522. */
  93523. get: function () {
  93524. return this._effectLayerOptions.camera;
  93525. },
  93526. enumerable: true,
  93527. configurable: true
  93528. });
  93529. /**
  93530. * Initializes the effect layer with the required options.
  93531. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93532. */
  93533. EffectLayer.prototype._init = function (options) {
  93534. // Adapt options
  93535. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93536. this._setMainTextureSize();
  93537. this._createMainTexture();
  93538. this._createTextureAndPostProcesses();
  93539. this._mergeEffect = this._createMergeEffect();
  93540. };
  93541. /**
  93542. * Generates the index buffer of the full screen quad blending to the main canvas.
  93543. */
  93544. EffectLayer.prototype._generateIndexBuffer = function () {
  93545. // Indices
  93546. var indices = [];
  93547. indices.push(0);
  93548. indices.push(1);
  93549. indices.push(2);
  93550. indices.push(0);
  93551. indices.push(2);
  93552. indices.push(3);
  93553. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93554. };
  93555. /**
  93556. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93557. */
  93558. EffectLayer.prototype._genrateVertexBuffer = function () {
  93559. // VBO
  93560. var vertices = [];
  93561. vertices.push(1, 1);
  93562. vertices.push(-1, 1);
  93563. vertices.push(-1, -1);
  93564. vertices.push(1, -1);
  93565. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93566. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93567. };
  93568. /**
  93569. * Sets the main texture desired size which is the closest power of two
  93570. * of the engine canvas size.
  93571. */
  93572. EffectLayer.prototype._setMainTextureSize = function () {
  93573. if (this._effectLayerOptions.mainTextureFixedSize) {
  93574. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93575. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93576. }
  93577. else {
  93578. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93579. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93580. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93581. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93582. }
  93583. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93584. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93585. };
  93586. /**
  93587. * Creates the main texture for the effect layer.
  93588. */
  93589. EffectLayer.prototype._createMainTexture = function () {
  93590. var _this = this;
  93591. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93592. width: this._mainTextureDesiredSize.width,
  93593. height: this._mainTextureDesiredSize.height
  93594. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93595. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93596. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93597. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93598. this._mainTexture.anisotropicFilteringLevel = 1;
  93599. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93600. this._mainTexture.renderParticles = false;
  93601. this._mainTexture.renderList = null;
  93602. this._mainTexture.ignoreCameraViewport = true;
  93603. // Custom render function
  93604. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93605. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93606. var index;
  93607. var engine = _this._scene.getEngine();
  93608. if (depthOnlySubMeshes.length) {
  93609. engine.setColorWrite(false);
  93610. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93611. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  93612. }
  93613. engine.setColorWrite(true);
  93614. }
  93615. for (index = 0; index < opaqueSubMeshes.length; index++) {
  93616. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  93617. }
  93618. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  93619. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  93620. }
  93621. for (index = 0; index < transparentSubMeshes.length; index++) {
  93622. _this._renderSubMesh(transparentSubMeshes.data[index]);
  93623. }
  93624. };
  93625. this._mainTexture.onClearObservable.add(function (engine) {
  93626. engine.clear(_this.neutralColor, true, true, true);
  93627. });
  93628. };
  93629. /**
  93630. * Checks for the readiness of the element composing the layer.
  93631. * @param subMesh the mesh to check for
  93632. * @param useInstances specify wether or not to use instances to render the mesh
  93633. * @param emissiveTexture the associated emissive texture used to generate the glow
  93634. * @return true if ready otherwise, false
  93635. */
  93636. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  93637. var material = subMesh.getMaterial();
  93638. if (!material) {
  93639. return false;
  93640. }
  93641. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  93642. return false;
  93643. }
  93644. var defines = [];
  93645. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93646. var mesh = subMesh.getMesh();
  93647. var uv1 = false;
  93648. var uv2 = false;
  93649. // Alpha test
  93650. if (material && material.needAlphaTesting()) {
  93651. var alphaTexture = material.getAlphaTestTexture();
  93652. if (alphaTexture) {
  93653. defines.push("#define ALPHATEST");
  93654. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93655. alphaTexture.coordinatesIndex === 1) {
  93656. defines.push("#define DIFFUSEUV2");
  93657. uv2 = true;
  93658. }
  93659. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93660. defines.push("#define DIFFUSEUV1");
  93661. uv1 = true;
  93662. }
  93663. }
  93664. }
  93665. // Emissive
  93666. if (emissiveTexture) {
  93667. defines.push("#define EMISSIVE");
  93668. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93669. emissiveTexture.coordinatesIndex === 1) {
  93670. defines.push("#define EMISSIVEUV2");
  93671. uv2 = true;
  93672. }
  93673. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93674. defines.push("#define EMISSIVEUV1");
  93675. uv1 = true;
  93676. }
  93677. }
  93678. if (uv1) {
  93679. attribs.push(BABYLON.VertexBuffer.UVKind);
  93680. defines.push("#define UV1");
  93681. }
  93682. if (uv2) {
  93683. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93684. defines.push("#define UV2");
  93685. }
  93686. // Bones
  93687. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93690. if (mesh.numBoneInfluencers > 4) {
  93691. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93692. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93693. }
  93694. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93695. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  93696. }
  93697. else {
  93698. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93699. }
  93700. // Morph targets
  93701. var manager = mesh.morphTargetManager;
  93702. var morphInfluencers = 0;
  93703. if (manager) {
  93704. if (manager.numInfluencers > 0) {
  93705. defines.push("#define MORPHTARGETS");
  93706. morphInfluencers = manager.numInfluencers;
  93707. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  93708. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  93709. }
  93710. }
  93711. // Instances
  93712. if (useInstances) {
  93713. defines.push("#define INSTANCES");
  93714. attribs.push("world0");
  93715. attribs.push("world1");
  93716. attribs.push("world2");
  93717. attribs.push("world3");
  93718. }
  93719. // Get correct effect
  93720. var join = defines.join("\n");
  93721. if (this._cachedDefines !== join) {
  93722. this._cachedDefines = join;
  93723. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  93724. }
  93725. return this._effectLayerMapGenerationEffect.isReady();
  93726. };
  93727. /**
  93728. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  93729. */
  93730. EffectLayer.prototype.render = function () {
  93731. var currentEffect = this._mergeEffect;
  93732. // Check
  93733. if (!currentEffect.isReady())
  93734. return;
  93735. for (var i = 0; i < this._postProcesses.length; i++) {
  93736. if (!this._postProcesses[i].isReady()) {
  93737. return;
  93738. }
  93739. }
  93740. var engine = this._scene.getEngine();
  93741. this.onBeforeComposeObservable.notifyObservers(this);
  93742. // Render
  93743. engine.enableEffect(currentEffect);
  93744. engine.setState(false);
  93745. // VBOs
  93746. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93747. // Cache
  93748. var previousAlphaMode = engine.getAlphaMode();
  93749. // Go Blend.
  93750. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  93751. // Blends the map on the main canvas.
  93752. this._internalRender(currentEffect);
  93753. // Restore Alpha
  93754. engine.setAlphaMode(previousAlphaMode);
  93755. this.onAfterComposeObservable.notifyObservers(this);
  93756. // Handle size changes.
  93757. var size = this._mainTexture.getSize();
  93758. this._setMainTextureSize();
  93759. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  93760. // Recreate RTT and post processes on size change.
  93761. this.onSizeChangedObservable.notifyObservers(this);
  93762. this._disposeTextureAndPostProcesses();
  93763. this._createMainTexture();
  93764. this._createTextureAndPostProcesses();
  93765. }
  93766. };
  93767. /**
  93768. * Determine if a given mesh will be used in the current effect.
  93769. * @param mesh mesh to test
  93770. * @returns true if the mesh will be used
  93771. */
  93772. EffectLayer.prototype.hasMesh = function (mesh) {
  93773. return true;
  93774. };
  93775. /**
  93776. * Returns true if the layer contains information to display, otherwise false.
  93777. * @returns true if the glow layer should be rendered
  93778. */
  93779. EffectLayer.prototype.shouldRender = function () {
  93780. return this.isEnabled && this._shouldRender;
  93781. };
  93782. /**
  93783. * Returns true if the mesh should render, otherwise false.
  93784. * @param mesh The mesh to render
  93785. * @returns true if it should render otherwise false
  93786. */
  93787. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  93788. return true;
  93789. };
  93790. /**
  93791. * Returns true if the mesh should render, otherwise false.
  93792. * @param mesh The mesh to render
  93793. * @returns true if it should render otherwise false
  93794. */
  93795. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  93796. return true;
  93797. };
  93798. /**
  93799. * Renders the submesh passed in parameter to the generation map.
  93800. */
  93801. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  93802. var _this = this;
  93803. if (!this.shouldRender()) {
  93804. return;
  93805. }
  93806. var material = subMesh.getMaterial();
  93807. var mesh = subMesh.getRenderingMesh();
  93808. var scene = this._scene;
  93809. var engine = scene.getEngine();
  93810. if (!material) {
  93811. return;
  93812. }
  93813. // Do not block in blend mode.
  93814. if (material.needAlphaBlendingForMesh(mesh)) {
  93815. return;
  93816. }
  93817. // Culling
  93818. engine.setState(material.backFaceCulling);
  93819. // Managing instances
  93820. var batch = mesh._getInstancesRenderList(subMesh._id);
  93821. if (batch.mustReturn) {
  93822. return;
  93823. }
  93824. // Early Exit per mesh
  93825. if (!this._shouldRenderMesh(mesh)) {
  93826. return;
  93827. }
  93828. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93829. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  93830. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  93831. engine.enableEffect(this._effectLayerMapGenerationEffect);
  93832. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  93833. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  93834. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  93835. // Alpha test
  93836. if (material && material.needAlphaTesting()) {
  93837. var alphaTexture = material.getAlphaTestTexture();
  93838. if (alphaTexture) {
  93839. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  93840. var textureMatrix = alphaTexture.getTextureMatrix();
  93841. if (textureMatrix) {
  93842. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  93843. }
  93844. }
  93845. }
  93846. // Glow emissive only
  93847. if (this._emissiveTextureAndColor.texture) {
  93848. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  93849. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  93850. }
  93851. // Bones
  93852. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93853. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93854. }
  93855. // Morph targets
  93856. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  93857. // Draw
  93858. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  93859. }
  93860. else {
  93861. // Need to reset refresh rate of the shadowMap
  93862. this._mainTexture.resetRefreshCounter();
  93863. }
  93864. };
  93865. /**
  93866. * Rebuild the required buffers.
  93867. * @hidden Internal use only.
  93868. */
  93869. EffectLayer.prototype._rebuild = function () {
  93870. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93871. if (vb) {
  93872. vb._rebuild();
  93873. }
  93874. this._generateIndexBuffer();
  93875. };
  93876. /**
  93877. * Dispose only the render target textures and post process.
  93878. */
  93879. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  93880. this._mainTexture.dispose();
  93881. for (var i = 0; i < this._postProcesses.length; i++) {
  93882. if (this._postProcesses[i]) {
  93883. this._postProcesses[i].dispose();
  93884. }
  93885. }
  93886. this._postProcesses = [];
  93887. for (var i = 0; i < this._textures.length; i++) {
  93888. if (this._textures[i]) {
  93889. this._textures[i].dispose();
  93890. }
  93891. }
  93892. this._textures = [];
  93893. };
  93894. /**
  93895. * Dispose the highlight layer and free resources.
  93896. */
  93897. EffectLayer.prototype.dispose = function () {
  93898. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93899. if (vertexBuffer) {
  93900. vertexBuffer.dispose();
  93901. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93902. }
  93903. if (this._indexBuffer) {
  93904. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93905. this._indexBuffer = null;
  93906. }
  93907. // Clean textures and post processes
  93908. this._disposeTextureAndPostProcesses();
  93909. // Remove from scene
  93910. var index = this._scene.effectLayers.indexOf(this, 0);
  93911. if (index > -1) {
  93912. this._scene.effectLayers.splice(index, 1);
  93913. }
  93914. // Callback
  93915. this.onDisposeObservable.notifyObservers(this);
  93916. this.onDisposeObservable.clear();
  93917. this.onBeforeRenderMainTextureObservable.clear();
  93918. this.onBeforeComposeObservable.clear();
  93919. this.onAfterComposeObservable.clear();
  93920. this.onSizeChangedObservable.clear();
  93921. };
  93922. /**
  93923. * Gets the class name of the effect layer
  93924. * @returns the string with the class name of the effect layer
  93925. */
  93926. EffectLayer.prototype.getClassName = function () {
  93927. return "EffectLayer";
  93928. };
  93929. /**
  93930. * Creates an effect layer from parsed effect layer data
  93931. * @param parsedEffectLayer defines effect layer data
  93932. * @param scene defines the current scene
  93933. * @param rootUrl defines the root URL containing the effect layer information
  93934. * @returns a parsed effect Layer
  93935. */
  93936. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  93937. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  93938. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  93939. };
  93940. __decorate([
  93941. BABYLON.serialize()
  93942. ], EffectLayer.prototype, "name", void 0);
  93943. __decorate([
  93944. BABYLON.serializeAsColor4()
  93945. ], EffectLayer.prototype, "neutralColor", void 0);
  93946. __decorate([
  93947. BABYLON.serialize()
  93948. ], EffectLayer.prototype, "isEnabled", void 0);
  93949. __decorate([
  93950. BABYLON.serializeAsCameraReference()
  93951. ], EffectLayer.prototype, "camera", null);
  93952. return EffectLayer;
  93953. }());
  93954. BABYLON.EffectLayer = EffectLayer;
  93955. })(BABYLON || (BABYLON = {}));
  93956. //# sourceMappingURL=babylon.effectLayer.js.map
  93957. var BABYLON;
  93958. (function (BABYLON) {
  93959. /**
  93960. * Special Glow Blur post process only blurring the alpha channel
  93961. * It enforces keeping the most luminous color in the color channel.
  93962. */
  93963. var GlowBlurPostProcess = /** @class */ (function (_super) {
  93964. __extends(GlowBlurPostProcess, _super);
  93965. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  93966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  93967. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  93968. _this.direction = direction;
  93969. _this.kernel = kernel;
  93970. _this.onApplyObservable.add(function (effect) {
  93971. effect.setFloat2("screenSize", _this.width, _this.height);
  93972. effect.setVector2("direction", _this.direction);
  93973. effect.setFloat("blurWidth", _this.kernel);
  93974. });
  93975. return _this;
  93976. }
  93977. return GlowBlurPostProcess;
  93978. }(BABYLON.PostProcess));
  93979. /**
  93980. * The highlight layer Helps adding a glow effect around a mesh.
  93981. *
  93982. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93983. * glowy meshes to your scene.
  93984. *
  93985. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  93986. */
  93987. var HighlightLayer = /** @class */ (function (_super) {
  93988. __extends(HighlightLayer, _super);
  93989. /**
  93990. * Instantiates a new highlight Layer and references it to the scene..
  93991. * @param name The name of the layer
  93992. * @param scene The scene to use the layer in
  93993. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  93994. */
  93995. function HighlightLayer(name, scene, options) {
  93996. var _this = _super.call(this, name, scene) || this;
  93997. _this.name = name;
  93998. /**
  93999. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94000. */
  94001. _this.innerGlow = true;
  94002. /**
  94003. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94004. */
  94005. _this.outerGlow = true;
  94006. /**
  94007. * An event triggered when the highlight layer is being blurred.
  94008. */
  94009. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94010. /**
  94011. * An event triggered when the highlight layer has been blurred.
  94012. */
  94013. _this.onAfterBlurObservable = new BABYLON.Observable();
  94014. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94015. _this._meshes = {};
  94016. _this._excludedMeshes = {};
  94017. _this.neutralColor = HighlightLayer.NeutralColor;
  94018. // Warn on stencil
  94019. if (!_this._engine.isStencilEnable) {
  94020. 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 }");
  94021. }
  94022. // Adapt options
  94023. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94024. // Initialize the layer
  94025. _this._init({
  94026. alphaBlendingMode: _this._options.alphaBlendingMode,
  94027. camera: _this._options.camera,
  94028. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94029. mainTextureRatio: _this._options.mainTextureRatio
  94030. });
  94031. // Do not render as long as no meshes have been added
  94032. _this._shouldRender = false;
  94033. return _this;
  94034. }
  94035. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94036. /**
  94037. * Gets the horizontal size of the blur.
  94038. */
  94039. get: function () {
  94040. return this._horizontalBlurPostprocess.kernel;
  94041. },
  94042. /**
  94043. * Specifies the horizontal size of the blur.
  94044. */
  94045. set: function (value) {
  94046. this._horizontalBlurPostprocess.kernel = value;
  94047. },
  94048. enumerable: true,
  94049. configurable: true
  94050. });
  94051. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94052. /**
  94053. * Gets the vertical size of the blur.
  94054. */
  94055. get: function () {
  94056. return this._verticalBlurPostprocess.kernel;
  94057. },
  94058. /**
  94059. * Specifies the vertical size of the blur.
  94060. */
  94061. set: function (value) {
  94062. this._verticalBlurPostprocess.kernel = value;
  94063. },
  94064. enumerable: true,
  94065. configurable: true
  94066. });
  94067. /**
  94068. * Get the effect name of the layer.
  94069. * @return The effect name
  94070. */
  94071. HighlightLayer.prototype.getEffectName = function () {
  94072. return HighlightLayer.EffectName;
  94073. };
  94074. /**
  94075. * Create the merge effect. This is the shader use to blit the information back
  94076. * to the main canvas at the end of the scene rendering.
  94077. */
  94078. HighlightLayer.prototype._createMergeEffect = function () {
  94079. // Effect
  94080. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94081. };
  94082. /**
  94083. * Creates the render target textures and post processes used in the highlight layer.
  94084. */
  94085. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94086. var _this = this;
  94087. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94088. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94089. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94090. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94091. var textureType = 0;
  94092. if (this._engine.getCaps().textureHalfFloatRender) {
  94093. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94094. }
  94095. else {
  94096. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94097. }
  94098. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94099. width: blurTextureWidth,
  94100. height: blurTextureHeight
  94101. }, this._scene, false, true, textureType);
  94102. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94103. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94104. this._blurTexture.anisotropicFilteringLevel = 16;
  94105. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94106. this._blurTexture.renderParticles = false;
  94107. this._blurTexture.ignoreCameraViewport = true;
  94108. this._textures = [this._blurTexture];
  94109. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94110. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94111. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94112. effect.setTexture("textureSampler", _this._mainTexture);
  94113. });
  94114. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94115. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94116. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94117. });
  94118. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94119. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94120. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94121. });
  94122. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94123. }
  94124. else {
  94125. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94126. width: blurTextureWidth,
  94127. height: blurTextureHeight
  94128. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94129. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94130. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94131. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94132. effect.setTexture("textureSampler", _this._mainTexture);
  94133. });
  94134. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94135. width: blurTextureWidth,
  94136. height: blurTextureHeight
  94137. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94138. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94139. }
  94140. this._mainTexture.onAfterUnbindObservable.add(function () {
  94141. _this.onBeforeBlurObservable.notifyObservers(_this);
  94142. var internalTexture = _this._blurTexture.getInternalTexture();
  94143. if (internalTexture) {
  94144. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94145. }
  94146. _this.onAfterBlurObservable.notifyObservers(_this);
  94147. });
  94148. // Prevent autoClear.
  94149. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94150. };
  94151. /**
  94152. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94153. */
  94154. HighlightLayer.prototype.needStencil = function () {
  94155. return true;
  94156. };
  94157. /**
  94158. * Checks for the readiness of the element composing the layer.
  94159. * @param subMesh the mesh to check for
  94160. * @param useInstances specify wether or not to use instances to render the mesh
  94161. * @param emissiveTexture the associated emissive texture used to generate the glow
  94162. * @return true if ready otherwise, false
  94163. */
  94164. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94165. var material = subMesh.getMaterial();
  94166. var mesh = subMesh.getRenderingMesh();
  94167. if (!material || !mesh || !this._meshes) {
  94168. return false;
  94169. }
  94170. var emissiveTexture = null;
  94171. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94172. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94173. emissiveTexture = material.emissiveTexture;
  94174. }
  94175. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94176. };
  94177. /**
  94178. * Implementation specific of rendering the generating effect on the main canvas.
  94179. * @param effect The effect used to render through
  94180. */
  94181. HighlightLayer.prototype._internalRender = function (effect) {
  94182. // Texture
  94183. effect.setTexture("textureSampler", this._blurTexture);
  94184. // Cache
  94185. var engine = this._engine;
  94186. var previousStencilBuffer = engine.getStencilBuffer();
  94187. var previousStencilFunction = engine.getStencilFunction();
  94188. var previousStencilMask = engine.getStencilMask();
  94189. var previousStencilOperationPass = engine.getStencilOperationPass();
  94190. var previousStencilOperationFail = engine.getStencilOperationFail();
  94191. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94192. var previousStencilReference = engine.getStencilFunctionReference();
  94193. // Stencil operations
  94194. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94195. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94196. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94197. // Draw order
  94198. engine.setStencilMask(0x00);
  94199. engine.setStencilBuffer(true);
  94200. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94201. // 2 passes inner outer
  94202. if (this.outerGlow) {
  94203. effect.setFloat("offset", 0);
  94204. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94205. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94206. }
  94207. if (this.innerGlow) {
  94208. effect.setFloat("offset", 1);
  94209. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94210. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94211. }
  94212. // Restore Cache
  94213. engine.setStencilFunction(previousStencilFunction);
  94214. engine.setStencilMask(previousStencilMask);
  94215. engine.setStencilBuffer(previousStencilBuffer);
  94216. engine.setStencilOperationPass(previousStencilOperationPass);
  94217. engine.setStencilOperationFail(previousStencilOperationFail);
  94218. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94219. engine.setStencilFunctionReference(previousStencilReference);
  94220. };
  94221. /**
  94222. * Returns true if the layer contains information to display, otherwise false.
  94223. */
  94224. HighlightLayer.prototype.shouldRender = function () {
  94225. if (_super.prototype.shouldRender.call(this)) {
  94226. return this._meshes ? true : false;
  94227. }
  94228. return false;
  94229. };
  94230. /**
  94231. * Returns true if the mesh should render, otherwise false.
  94232. * @param mesh The mesh to render
  94233. * @returns true if it should render otherwise false
  94234. */
  94235. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94236. // Excluded Mesh
  94237. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94238. return false;
  94239. }
  94240. ;
  94241. return true;
  94242. };
  94243. /**
  94244. * Sets the required values for both the emissive texture and and the main color.
  94245. */
  94246. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94247. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94248. if (highlightLayerMesh) {
  94249. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94250. }
  94251. else {
  94252. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94253. }
  94254. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94255. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94256. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94257. }
  94258. else {
  94259. this._emissiveTextureAndColor.texture = null;
  94260. }
  94261. };
  94262. /**
  94263. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94264. * @param mesh The mesh to exclude from the highlight layer
  94265. */
  94266. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94267. if (!this._excludedMeshes) {
  94268. return;
  94269. }
  94270. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94271. if (!meshExcluded) {
  94272. this._excludedMeshes[mesh.uniqueId] = {
  94273. mesh: mesh,
  94274. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94275. mesh.getEngine().setStencilBuffer(false);
  94276. }),
  94277. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94278. mesh.getEngine().setStencilBuffer(true);
  94279. }),
  94280. };
  94281. }
  94282. };
  94283. /**
  94284. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94285. * @param mesh The mesh to highlight
  94286. */
  94287. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94288. if (!this._excludedMeshes) {
  94289. return;
  94290. }
  94291. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94292. if (meshExcluded) {
  94293. if (meshExcluded.beforeRender) {
  94294. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94295. }
  94296. if (meshExcluded.afterRender) {
  94297. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94298. }
  94299. }
  94300. this._excludedMeshes[mesh.uniqueId] = null;
  94301. };
  94302. /**
  94303. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94304. * @param mesh mesh to test
  94305. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94306. */
  94307. HighlightLayer.prototype.hasMesh = function (mesh) {
  94308. if (!this._meshes) {
  94309. return false;
  94310. }
  94311. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94312. };
  94313. /**
  94314. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94315. * @param mesh The mesh to highlight
  94316. * @param color The color of the highlight
  94317. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94318. */
  94319. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94320. var _this = this;
  94321. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94322. if (!this._meshes) {
  94323. return;
  94324. }
  94325. var meshHighlight = this._meshes[mesh.uniqueId];
  94326. if (meshHighlight) {
  94327. meshHighlight.color = color;
  94328. }
  94329. else {
  94330. this._meshes[mesh.uniqueId] = {
  94331. mesh: mesh,
  94332. color: color,
  94333. // Lambda required for capture due to Observable this context
  94334. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94335. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94336. _this._defaultStencilReference(mesh);
  94337. }
  94338. else {
  94339. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94340. }
  94341. }),
  94342. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94343. glowEmissiveOnly: glowEmissiveOnly
  94344. };
  94345. }
  94346. this._shouldRender = true;
  94347. };
  94348. /**
  94349. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94350. * @param mesh The mesh to highlight
  94351. */
  94352. HighlightLayer.prototype.removeMesh = function (mesh) {
  94353. if (!this._meshes) {
  94354. return;
  94355. }
  94356. var meshHighlight = this._meshes[mesh.uniqueId];
  94357. if (meshHighlight) {
  94358. if (meshHighlight.observerHighlight) {
  94359. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94360. }
  94361. if (meshHighlight.observerDefault) {
  94362. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94363. }
  94364. delete this._meshes[mesh.uniqueId];
  94365. }
  94366. this._shouldRender = false;
  94367. for (var meshHighlightToCheck in this._meshes) {
  94368. if (this._meshes[meshHighlightToCheck]) {
  94369. this._shouldRender = true;
  94370. break;
  94371. }
  94372. }
  94373. };
  94374. /**
  94375. * Force the stencil to the normal expected value for none glowing parts
  94376. */
  94377. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94378. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94379. };
  94380. /**
  94381. * Free any resources and references associated to a mesh.
  94382. * Internal use
  94383. * @param mesh The mesh to free.
  94384. */
  94385. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94386. this.removeMesh(mesh);
  94387. this.removeExcludedMesh(mesh);
  94388. };
  94389. /**
  94390. * Dispose the highlight layer and free resources.
  94391. */
  94392. HighlightLayer.prototype.dispose = function () {
  94393. if (this._meshes) {
  94394. // Clean mesh references
  94395. for (var id in this._meshes) {
  94396. var meshHighlight = this._meshes[id];
  94397. if (meshHighlight && meshHighlight.mesh) {
  94398. if (meshHighlight.observerHighlight) {
  94399. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94400. }
  94401. if (meshHighlight.observerDefault) {
  94402. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94403. }
  94404. }
  94405. }
  94406. this._meshes = null;
  94407. }
  94408. if (this._excludedMeshes) {
  94409. for (var id in this._excludedMeshes) {
  94410. var meshHighlight = this._excludedMeshes[id];
  94411. if (meshHighlight) {
  94412. if (meshHighlight.beforeRender) {
  94413. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94414. }
  94415. if (meshHighlight.afterRender) {
  94416. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94417. }
  94418. }
  94419. }
  94420. this._excludedMeshes = null;
  94421. }
  94422. _super.prototype.dispose.call(this);
  94423. };
  94424. /**
  94425. * Gets the class name of the effect layer
  94426. * @returns the string with the class name of the effect layer
  94427. */
  94428. HighlightLayer.prototype.getClassName = function () {
  94429. return "HighlightLayer";
  94430. };
  94431. /**
  94432. * Serializes this Highlight layer
  94433. * @returns a serialized Highlight layer object
  94434. */
  94435. HighlightLayer.prototype.serialize = function () {
  94436. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94437. serializationObject.customType = "BABYLON.HighlightLayer";
  94438. // Highlighted meshes
  94439. serializationObject.meshes = [];
  94440. if (this._meshes) {
  94441. for (var m in this._meshes) {
  94442. var mesh = this._meshes[m];
  94443. if (mesh) {
  94444. serializationObject.meshes.push({
  94445. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94446. color: mesh.color.asArray(),
  94447. meshId: mesh.mesh.id
  94448. });
  94449. }
  94450. }
  94451. }
  94452. // Excluded meshes
  94453. serializationObject.excludedMeshes = [];
  94454. if (this._excludedMeshes) {
  94455. for (var e in this._excludedMeshes) {
  94456. var excludedMesh = this._excludedMeshes[e];
  94457. if (excludedMesh) {
  94458. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94459. }
  94460. }
  94461. }
  94462. return serializationObject;
  94463. };
  94464. /**
  94465. * Creates a Highlight layer from parsed Highlight layer data
  94466. * @param parsedHightlightLayer defines the Highlight layer data
  94467. * @param scene defines the current scene
  94468. * @param rootUrl defines the root URL containing the Highlight layer information
  94469. * @returns a parsed Highlight layer
  94470. */
  94471. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94472. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94473. var index;
  94474. // Excluded meshes
  94475. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94476. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94477. if (mesh) {
  94478. hl.addExcludedMesh(mesh);
  94479. }
  94480. }
  94481. // Included meshes
  94482. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94483. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94484. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94485. if (mesh) {
  94486. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94487. }
  94488. }
  94489. return hl;
  94490. };
  94491. /**
  94492. * Effect Name of the highlight layer.
  94493. */
  94494. HighlightLayer.EffectName = "HighlightLayer";
  94495. /**
  94496. * The neutral color used during the preparation of the glow effect.
  94497. * This is black by default as the blend operation is a blend operation.
  94498. */
  94499. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94500. /**
  94501. * Stencil value used for glowing meshes.
  94502. */
  94503. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94504. /**
  94505. * Stencil value used for the other meshes in the scene.
  94506. */
  94507. HighlightLayer.NormalMeshStencilReference = 0x01;
  94508. __decorate([
  94509. BABYLON.serialize()
  94510. ], HighlightLayer.prototype, "innerGlow", void 0);
  94511. __decorate([
  94512. BABYLON.serialize()
  94513. ], HighlightLayer.prototype, "outerGlow", void 0);
  94514. __decorate([
  94515. BABYLON.serialize()
  94516. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94517. __decorate([
  94518. BABYLON.serialize()
  94519. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94520. __decorate([
  94521. BABYLON.serialize("options")
  94522. ], HighlightLayer.prototype, "_options", void 0);
  94523. return HighlightLayer;
  94524. }(BABYLON.EffectLayer));
  94525. BABYLON.HighlightLayer = HighlightLayer;
  94526. })(BABYLON || (BABYLON = {}));
  94527. //# sourceMappingURL=babylon.highlightLayer.js.map
  94528. var BABYLON;
  94529. (function (BABYLON) {
  94530. /**
  94531. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94532. *
  94533. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94534. * glowy meshes to your scene.
  94535. *
  94536. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94537. */
  94538. var GlowLayer = /** @class */ (function (_super) {
  94539. __extends(GlowLayer, _super);
  94540. /**
  94541. * Instantiates a new glow Layer and references it to the scene.
  94542. * @param name The name of the layer
  94543. * @param scene The scene to use the layer in
  94544. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94545. */
  94546. function GlowLayer(name, scene, options) {
  94547. var _this = _super.call(this, name, scene) || this;
  94548. _this._intensity = 1.0;
  94549. _this._includedOnlyMeshes = [];
  94550. _this._excludedMeshes = [];
  94551. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94552. // Adapt options
  94553. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94554. // Initialize the layer
  94555. _this._init({
  94556. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94557. camera: _this._options.camera,
  94558. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94559. mainTextureRatio: _this._options.mainTextureRatio
  94560. });
  94561. return _this;
  94562. }
  94563. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94564. /**
  94565. * Gets the kernel size of the blur.
  94566. */
  94567. get: function () {
  94568. return this._horizontalBlurPostprocess1.kernel;
  94569. },
  94570. /**
  94571. * Sets the kernel size of the blur.
  94572. */
  94573. set: function (value) {
  94574. this._horizontalBlurPostprocess1.kernel = value;
  94575. this._verticalBlurPostprocess1.kernel = value;
  94576. this._horizontalBlurPostprocess2.kernel = value;
  94577. this._verticalBlurPostprocess2.kernel = value;
  94578. },
  94579. enumerable: true,
  94580. configurable: true
  94581. });
  94582. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94583. /**
  94584. * Gets the glow intensity.
  94585. */
  94586. get: function () {
  94587. return this._intensity;
  94588. },
  94589. /**
  94590. * Sets the glow intensity.
  94591. */
  94592. set: function (value) {
  94593. this._intensity = value;
  94594. },
  94595. enumerable: true,
  94596. configurable: true
  94597. });
  94598. /**
  94599. * Get the effect name of the layer.
  94600. * @return The effect name
  94601. */
  94602. GlowLayer.prototype.getEffectName = function () {
  94603. return GlowLayer.EffectName;
  94604. };
  94605. /**
  94606. * Create the merge effect. This is the shader use to blit the information back
  94607. * to the main canvas at the end of the scene rendering.
  94608. */
  94609. GlowLayer.prototype._createMergeEffect = function () {
  94610. // Effect
  94611. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  94612. };
  94613. /**
  94614. * Creates the render target textures and post processes used in the glow layer.
  94615. */
  94616. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  94617. var _this = this;
  94618. var blurTextureWidth = this._mainTextureDesiredSize.width;
  94619. var blurTextureHeight = this._mainTextureDesiredSize.height;
  94620. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94621. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94622. var textureType = 0;
  94623. if (this._engine.getCaps().textureHalfFloatRender) {
  94624. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94625. }
  94626. else {
  94627. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94628. }
  94629. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  94630. width: blurTextureWidth,
  94631. height: blurTextureHeight
  94632. }, this._scene, false, true, textureType);
  94633. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94634. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94635. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94636. this._blurTexture1.renderParticles = false;
  94637. this._blurTexture1.ignoreCameraViewport = true;
  94638. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  94639. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  94640. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  94641. width: blurTextureWidth2,
  94642. height: blurTextureHeight2
  94643. }, this._scene, false, true, textureType);
  94644. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94645. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94646. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94647. this._blurTexture2.renderParticles = false;
  94648. this._blurTexture2.ignoreCameraViewport = true;
  94649. this._textures = [this._blurTexture1, this._blurTexture2];
  94650. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94651. width: blurTextureWidth,
  94652. height: blurTextureHeight
  94653. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94654. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  94655. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  94656. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  94657. effect.setTexture("textureSampler", _this._mainTexture);
  94658. });
  94659. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94660. width: blurTextureWidth,
  94661. height: blurTextureHeight
  94662. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94663. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94664. width: blurTextureWidth2,
  94665. height: blurTextureHeight2
  94666. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94667. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  94668. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  94669. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  94670. effect.setTexture("textureSampler", _this._blurTexture1);
  94671. });
  94672. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94673. width: blurTextureWidth2,
  94674. height: blurTextureHeight2
  94675. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94676. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94677. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  94678. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94679. this._mainTexture.samples = this._options.mainTextureSamples;
  94680. this._mainTexture.onAfterUnbindObservable.add(function () {
  94681. var internalTexture = _this._blurTexture1.getInternalTexture();
  94682. if (internalTexture) {
  94683. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  94684. internalTexture = _this._blurTexture2.getInternalTexture();
  94685. if (internalTexture) {
  94686. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  94687. }
  94688. }
  94689. });
  94690. // Prevent autoClear.
  94691. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94692. };
  94693. /**
  94694. * Checks for the readiness of the element composing the layer.
  94695. * @param subMesh the mesh to check for
  94696. * @param useInstances specify wether or not to use instances to render the mesh
  94697. * @param emissiveTexture the associated emissive texture used to generate the glow
  94698. * @return true if ready otherwise, false
  94699. */
  94700. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  94701. var material = subMesh.getMaterial();
  94702. var mesh = subMesh.getRenderingMesh();
  94703. if (!material || !mesh) {
  94704. return false;
  94705. }
  94706. var emissiveTexture = material.emissiveTexture;
  94707. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94708. };
  94709. /**
  94710. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94711. */
  94712. GlowLayer.prototype.needStencil = function () {
  94713. return false;
  94714. };
  94715. /**
  94716. * Implementation specific of rendering the generating effect on the main canvas.
  94717. * @param effect The effect used to render through
  94718. */
  94719. GlowLayer.prototype._internalRender = function (effect) {
  94720. // Texture
  94721. effect.setTexture("textureSampler", this._blurTexture1);
  94722. effect.setTexture("textureSampler2", this._blurTexture2);
  94723. effect.setFloat("offset", this._intensity);
  94724. // Cache
  94725. var engine = this._engine;
  94726. var previousStencilBuffer = engine.getStencilBuffer();
  94727. // Draw order
  94728. engine.setStencilBuffer(false);
  94729. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94730. // Draw order
  94731. engine.setStencilBuffer(previousStencilBuffer);
  94732. };
  94733. /**
  94734. * Sets the required values for both the emissive texture and and the main color.
  94735. */
  94736. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94737. var textureLevel = 1.0;
  94738. if (this.customEmissiveTextureSelector) {
  94739. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  94740. }
  94741. else {
  94742. if (material) {
  94743. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94744. if (this._emissiveTextureAndColor.texture) {
  94745. textureLevel = this._emissiveTextureAndColor.texture.level;
  94746. }
  94747. }
  94748. else {
  94749. this._emissiveTextureAndColor.texture = null;
  94750. }
  94751. }
  94752. if (this.customEmissiveColorSelector) {
  94753. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  94754. }
  94755. else {
  94756. if (material.emissiveColor) {
  94757. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  94758. }
  94759. else {
  94760. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94761. }
  94762. }
  94763. };
  94764. /**
  94765. * Returns true if the mesh should render, otherwise false.
  94766. * @param mesh The mesh to render
  94767. * @returns true if it should render otherwise false
  94768. */
  94769. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  94770. return this.hasMesh(mesh);
  94771. };
  94772. /**
  94773. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  94774. * @param mesh The mesh to exclude from the glow layer
  94775. */
  94776. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  94777. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  94778. this._excludedMeshes.push(mesh.uniqueId);
  94779. }
  94780. };
  94781. /**
  94782. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  94783. * @param mesh The mesh to remove
  94784. */
  94785. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  94786. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  94787. if (index !== -1) {
  94788. this._excludedMeshes.splice(index, 1);
  94789. }
  94790. };
  94791. /**
  94792. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  94793. * @param mesh The mesh to include in the glow layer
  94794. */
  94795. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  94796. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  94797. this._includedOnlyMeshes.push(mesh.uniqueId);
  94798. }
  94799. };
  94800. /**
  94801. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  94802. * @param mesh The mesh to remove
  94803. */
  94804. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  94805. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  94806. if (index !== -1) {
  94807. this._includedOnlyMeshes.splice(index, 1);
  94808. }
  94809. };
  94810. /**
  94811. * Determine if a given mesh will be used in the glow layer
  94812. * @param mesh The mesh to test
  94813. * @returns true if the mesh will be highlighted by the current glow layer
  94814. */
  94815. GlowLayer.prototype.hasMesh = function (mesh) {
  94816. // Included Mesh
  94817. if (this._includedOnlyMeshes.length) {
  94818. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  94819. }
  94820. ;
  94821. // Excluded Mesh
  94822. if (this._excludedMeshes.length) {
  94823. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  94824. }
  94825. ;
  94826. return true;
  94827. };
  94828. /**
  94829. * Free any resources and references associated to a mesh.
  94830. * Internal use
  94831. * @param mesh The mesh to free.
  94832. */
  94833. GlowLayer.prototype._disposeMesh = function (mesh) {
  94834. this.removeIncludedOnlyMesh(mesh);
  94835. this.removeExcludedMesh(mesh);
  94836. };
  94837. /**
  94838. * Gets the class name of the effect layer
  94839. * @returns the string with the class name of the effect layer
  94840. */
  94841. GlowLayer.prototype.getClassName = function () {
  94842. return "GlowLayer";
  94843. };
  94844. /**
  94845. * Serializes this glow layer
  94846. * @returns a serialized glow layer object
  94847. */
  94848. GlowLayer.prototype.serialize = function () {
  94849. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94850. serializationObject.customType = "BABYLON.GlowLayer";
  94851. var index;
  94852. // Included meshes
  94853. serializationObject.includedMeshes = [];
  94854. if (this._includedOnlyMeshes.length) {
  94855. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  94856. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  94857. if (mesh) {
  94858. serializationObject.includedMeshes.push(mesh.id);
  94859. }
  94860. }
  94861. }
  94862. // Excluded meshes
  94863. serializationObject.excludedMeshes = [];
  94864. if (this._excludedMeshes.length) {
  94865. for (index = 0; index < this._excludedMeshes.length; index++) {
  94866. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  94867. if (mesh) {
  94868. serializationObject.excludedMeshes.push(mesh.id);
  94869. }
  94870. }
  94871. }
  94872. return serializationObject;
  94873. };
  94874. /**
  94875. * Creates a Glow Layer from parsed glow layer data
  94876. * @param parsedGlowLayer defines glow layer data
  94877. * @param scene defines the current scene
  94878. * @param rootUrl defines the root URL containing the glow layer information
  94879. * @returns a parsed Glow Layer
  94880. */
  94881. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  94882. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  94883. var index;
  94884. // Excluded meshes
  94885. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  94886. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  94887. if (mesh) {
  94888. gl.addExcludedMesh(mesh);
  94889. }
  94890. }
  94891. // Included meshes
  94892. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  94893. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  94894. if (mesh) {
  94895. gl.addIncludedOnlyMesh(mesh);
  94896. }
  94897. }
  94898. return gl;
  94899. };
  94900. /**
  94901. * Effect Name of the layer.
  94902. */
  94903. GlowLayer.EffectName = "GlowLayer";
  94904. /**
  94905. * The default blur kernel size used for the glow.
  94906. */
  94907. GlowLayer.DefaultBlurKernelSize = 32;
  94908. /**
  94909. * The default texture size ratio used for the glow.
  94910. */
  94911. GlowLayer.DefaultTextureRatio = 0.5;
  94912. __decorate([
  94913. BABYLON.serialize()
  94914. ], GlowLayer.prototype, "blurKernelSize", null);
  94915. __decorate([
  94916. BABYLON.serialize()
  94917. ], GlowLayer.prototype, "intensity", null);
  94918. __decorate([
  94919. BABYLON.serialize("options")
  94920. ], GlowLayer.prototype, "_options", void 0);
  94921. return GlowLayer;
  94922. }(BABYLON.EffectLayer));
  94923. BABYLON.GlowLayer = GlowLayer;
  94924. })(BABYLON || (BABYLON = {}));
  94925. //# sourceMappingURL=babylon.glowLayer.js.map
  94926. var BABYLON;
  94927. (function (BABYLON) {
  94928. /**
  94929. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  94930. */
  94931. var AssetTaskState;
  94932. (function (AssetTaskState) {
  94933. /**
  94934. * Initialization
  94935. */
  94936. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  94937. /**
  94938. * Running
  94939. */
  94940. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  94941. /**
  94942. * Done
  94943. */
  94944. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  94945. /**
  94946. * Error
  94947. */
  94948. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  94949. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  94950. /**
  94951. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  94952. */
  94953. var AbstractAssetTask = /** @class */ (function () {
  94954. /**
  94955. * Creates a new {BABYLON.AssetsManager}
  94956. * @param name defines the name of the task
  94957. */
  94958. function AbstractAssetTask(
  94959. /**
  94960. * Task name
  94961. */ name) {
  94962. this.name = name;
  94963. this._isCompleted = false;
  94964. this._taskState = AssetTaskState.INIT;
  94965. }
  94966. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  94967. /**
  94968. * Get if the task is completed
  94969. */
  94970. get: function () {
  94971. return this._isCompleted;
  94972. },
  94973. enumerable: true,
  94974. configurable: true
  94975. });
  94976. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  94977. /**
  94978. * Gets the current state of the task
  94979. */
  94980. get: function () {
  94981. return this._taskState;
  94982. },
  94983. enumerable: true,
  94984. configurable: true
  94985. });
  94986. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  94987. /**
  94988. * Gets the current error object (if task is in error)
  94989. */
  94990. get: function () {
  94991. return this._errorObject;
  94992. },
  94993. enumerable: true,
  94994. configurable: true
  94995. });
  94996. /**
  94997. * Internal only
  94998. * @hidden
  94999. */
  95000. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95001. if (this._errorObject) {
  95002. return;
  95003. }
  95004. this._errorObject = {
  95005. message: message,
  95006. exception: exception
  95007. };
  95008. };
  95009. /**
  95010. * Execute the current task
  95011. * @param scene defines the scene where you want your assets to be loaded
  95012. * @param onSuccess is a callback called when the task is successfully executed
  95013. * @param onError is a callback called if an error occurs
  95014. */
  95015. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95016. var _this = this;
  95017. this._taskState = AssetTaskState.RUNNING;
  95018. this.runTask(scene, function () {
  95019. _this.onDoneCallback(onSuccess, onError);
  95020. }, function (msg, exception) {
  95021. _this.onErrorCallback(onError, msg, exception);
  95022. });
  95023. };
  95024. /**
  95025. * Execute the current task
  95026. * @param scene defines the scene where you want your assets to be loaded
  95027. * @param onSuccess is a callback called when the task is successfully executed
  95028. * @param onError is a callback called if an error occurs
  95029. */
  95030. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95031. throw new Error("runTask is not implemented");
  95032. };
  95033. /**
  95034. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95035. * This can be used with failed tasks that have the reason for failure fixed.
  95036. */
  95037. AbstractAssetTask.prototype.reset = function () {
  95038. this._taskState = AssetTaskState.INIT;
  95039. };
  95040. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95041. this._taskState = AssetTaskState.ERROR;
  95042. this._errorObject = {
  95043. message: message,
  95044. exception: exception
  95045. };
  95046. if (this.onError) {
  95047. this.onError(this, message, exception);
  95048. }
  95049. onError();
  95050. };
  95051. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95052. try {
  95053. this._taskState = AssetTaskState.DONE;
  95054. this._isCompleted = true;
  95055. if (this.onSuccess) {
  95056. this.onSuccess(this);
  95057. }
  95058. onSuccess();
  95059. }
  95060. catch (e) {
  95061. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95062. }
  95063. };
  95064. return AbstractAssetTask;
  95065. }());
  95066. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95067. /**
  95068. * Class used to share progress information about assets loading
  95069. */
  95070. var AssetsProgressEvent = /** @class */ (function () {
  95071. /**
  95072. * Creates a {BABYLON.AssetsProgressEvent}
  95073. * @param remainingCount defines the number of remaining tasks to process
  95074. * @param totalCount defines the total number of tasks
  95075. * @param task defines the task that was just processed
  95076. */
  95077. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95078. this.remainingCount = remainingCount;
  95079. this.totalCount = totalCount;
  95080. this.task = task;
  95081. }
  95082. return AssetsProgressEvent;
  95083. }());
  95084. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95085. /**
  95086. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95087. */
  95088. var MeshAssetTask = /** @class */ (function (_super) {
  95089. __extends(MeshAssetTask, _super);
  95090. /**
  95091. * Creates a new {BABYLON.MeshAssetTask}
  95092. * @param name defines the name of the task
  95093. * @param meshesNames defines the list of mesh's names you want to load
  95094. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95095. * @param sceneFilename defines the filename of the scene to load from
  95096. */
  95097. function MeshAssetTask(
  95098. /**
  95099. * Defines the name of the task
  95100. */
  95101. name,
  95102. /**
  95103. * Defines the list of mesh's names you want to load
  95104. */
  95105. meshesNames,
  95106. /**
  95107. * Defines the root url to use as a base to load your meshes and associated resources
  95108. */
  95109. rootUrl,
  95110. /**
  95111. * Defines the filename of the scene to load from
  95112. */
  95113. sceneFilename) {
  95114. var _this = _super.call(this, name) || this;
  95115. _this.name = name;
  95116. _this.meshesNames = meshesNames;
  95117. _this.rootUrl = rootUrl;
  95118. _this.sceneFilename = sceneFilename;
  95119. return _this;
  95120. }
  95121. /**
  95122. * Execute the current task
  95123. * @param scene defines the scene where you want your assets to be loaded
  95124. * @param onSuccess is a callback called when the task is successfully executed
  95125. * @param onError is a callback called if an error occurs
  95126. */
  95127. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95128. var _this = this;
  95129. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95130. _this.loadedMeshes = meshes;
  95131. _this.loadedParticleSystems = particleSystems;
  95132. _this.loadedSkeletons = skeletons;
  95133. onSuccess();
  95134. }, null, function (scene, message, exception) {
  95135. onError(message, exception);
  95136. });
  95137. };
  95138. return MeshAssetTask;
  95139. }(AbstractAssetTask));
  95140. BABYLON.MeshAssetTask = MeshAssetTask;
  95141. /**
  95142. * Define a task used by {BABYLON.AssetsManager} to load text content
  95143. */
  95144. var TextFileAssetTask = /** @class */ (function (_super) {
  95145. __extends(TextFileAssetTask, _super);
  95146. /**
  95147. * Creates a new TextFileAssetTask object
  95148. * @param name defines the name of the task
  95149. * @param url defines the location of the file to load
  95150. */
  95151. function TextFileAssetTask(
  95152. /**
  95153. * Defines the name of the task
  95154. */
  95155. name,
  95156. /**
  95157. * Defines the location of the file to load
  95158. */
  95159. url) {
  95160. var _this = _super.call(this, name) || this;
  95161. _this.name = name;
  95162. _this.url = url;
  95163. return _this;
  95164. }
  95165. /**
  95166. * Execute the current task
  95167. * @param scene defines the scene where you want your assets to be loaded
  95168. * @param onSuccess is a callback called when the task is successfully executed
  95169. * @param onError is a callback called if an error occurs
  95170. */
  95171. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95172. var _this = this;
  95173. scene._loadFile(this.url, function (data) {
  95174. _this.text = data;
  95175. onSuccess();
  95176. }, undefined, false, false, function (request, exception) {
  95177. if (request) {
  95178. onError(request.status + " " + request.statusText, exception);
  95179. }
  95180. });
  95181. };
  95182. return TextFileAssetTask;
  95183. }(AbstractAssetTask));
  95184. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95185. /**
  95186. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95187. */
  95188. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95189. __extends(BinaryFileAssetTask, _super);
  95190. /**
  95191. * Creates a new BinaryFileAssetTask object
  95192. * @param name defines the name of the new task
  95193. * @param url defines the location of the file to load
  95194. */
  95195. function BinaryFileAssetTask(
  95196. /**
  95197. * Defines the name of the task
  95198. */
  95199. name,
  95200. /**
  95201. * Defines the location of the file to load
  95202. */
  95203. url) {
  95204. var _this = _super.call(this, name) || this;
  95205. _this.name = name;
  95206. _this.url = url;
  95207. return _this;
  95208. }
  95209. /**
  95210. * Execute the current task
  95211. * @param scene defines the scene where you want your assets to be loaded
  95212. * @param onSuccess is a callback called when the task is successfully executed
  95213. * @param onError is a callback called if an error occurs
  95214. */
  95215. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95216. var _this = this;
  95217. scene._loadFile(this.url, function (data) {
  95218. _this.data = data;
  95219. onSuccess();
  95220. }, undefined, true, true, function (request, exception) {
  95221. if (request) {
  95222. onError(request.status + " " + request.statusText, exception);
  95223. }
  95224. });
  95225. };
  95226. return BinaryFileAssetTask;
  95227. }(AbstractAssetTask));
  95228. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95229. /**
  95230. * Define a task used by {BABYLON.AssetsManager} to load images
  95231. */
  95232. var ImageAssetTask = /** @class */ (function (_super) {
  95233. __extends(ImageAssetTask, _super);
  95234. /**
  95235. * Creates a new ImageAssetTask
  95236. * @param name defines the name of the task
  95237. * @param url defines the location of the image to load
  95238. */
  95239. function ImageAssetTask(
  95240. /**
  95241. * Defines the name of the task
  95242. */
  95243. name,
  95244. /**
  95245. * Defines the location of the image to load
  95246. */
  95247. url) {
  95248. var _this = _super.call(this, name) || this;
  95249. _this.name = name;
  95250. _this.url = url;
  95251. return _this;
  95252. }
  95253. /**
  95254. * Execute the current task
  95255. * @param scene defines the scene where you want your assets to be loaded
  95256. * @param onSuccess is a callback called when the task is successfully executed
  95257. * @param onError is a callback called if an error occurs
  95258. */
  95259. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95260. var _this = this;
  95261. var img = new Image();
  95262. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95263. img.onload = function () {
  95264. _this.image = img;
  95265. onSuccess();
  95266. };
  95267. img.onerror = function (err) {
  95268. onError("Error loading image", err);
  95269. };
  95270. img.src = this.url;
  95271. };
  95272. return ImageAssetTask;
  95273. }(AbstractAssetTask));
  95274. BABYLON.ImageAssetTask = ImageAssetTask;
  95275. /**
  95276. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95277. */
  95278. var TextureAssetTask = /** @class */ (function (_super) {
  95279. __extends(TextureAssetTask, _super);
  95280. /**
  95281. * Creates a new TextureAssetTask object
  95282. * @param name defines the name of the task
  95283. * @param url defines the location of the file to load
  95284. * @param noMipmap defines if mipmap should not be generated (default is false)
  95285. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95286. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95287. */
  95288. function TextureAssetTask(
  95289. /**
  95290. * Defines the name of the task
  95291. */
  95292. name,
  95293. /**
  95294. * Defines the location of the file to load
  95295. */
  95296. url,
  95297. /**
  95298. * Defines if mipmap should not be generated (default is false)
  95299. */
  95300. noMipmap,
  95301. /**
  95302. * Defines if texture must be inverted on Y axis (default is false)
  95303. */
  95304. invertY,
  95305. /**
  95306. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95307. */
  95308. samplingMode) {
  95309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95310. var _this = _super.call(this, name) || this;
  95311. _this.name = name;
  95312. _this.url = url;
  95313. _this.noMipmap = noMipmap;
  95314. _this.invertY = invertY;
  95315. _this.samplingMode = samplingMode;
  95316. return _this;
  95317. }
  95318. /**
  95319. * Execute the current task
  95320. * @param scene defines the scene where you want your assets to be loaded
  95321. * @param onSuccess is a callback called when the task is successfully executed
  95322. * @param onError is a callback called if an error occurs
  95323. */
  95324. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95325. var onload = function () {
  95326. onSuccess();
  95327. };
  95328. var onerror = function (message, exception) {
  95329. onError(message, exception);
  95330. };
  95331. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95332. };
  95333. return TextureAssetTask;
  95334. }(AbstractAssetTask));
  95335. BABYLON.TextureAssetTask = TextureAssetTask;
  95336. /**
  95337. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95338. */
  95339. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95340. __extends(CubeTextureAssetTask, _super);
  95341. /**
  95342. * Creates a new CubeTextureAssetTask
  95343. * @param name defines the name of the task
  95344. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95345. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95346. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95347. * @param files defines the explicit list of files (undefined by default)
  95348. */
  95349. function CubeTextureAssetTask(
  95350. /**
  95351. * Defines the name of the task
  95352. */
  95353. name,
  95354. /**
  95355. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95356. */
  95357. url,
  95358. /**
  95359. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95360. */
  95361. extensions,
  95362. /**
  95363. * Defines if mipmaps should not be generated (default is false)
  95364. */
  95365. noMipmap,
  95366. /**
  95367. * Defines the explicit list of files (undefined by default)
  95368. */
  95369. files) {
  95370. var _this = _super.call(this, name) || this;
  95371. _this.name = name;
  95372. _this.url = url;
  95373. _this.extensions = extensions;
  95374. _this.noMipmap = noMipmap;
  95375. _this.files = files;
  95376. return _this;
  95377. }
  95378. /**
  95379. * Execute the current task
  95380. * @param scene defines the scene where you want your assets to be loaded
  95381. * @param onSuccess is a callback called when the task is successfully executed
  95382. * @param onError is a callback called if an error occurs
  95383. */
  95384. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95385. var onload = function () {
  95386. onSuccess();
  95387. };
  95388. var onerror = function (message, exception) {
  95389. onError(message, exception);
  95390. };
  95391. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95392. };
  95393. return CubeTextureAssetTask;
  95394. }(AbstractAssetTask));
  95395. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95396. /**
  95397. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95398. */
  95399. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95400. __extends(HDRCubeTextureAssetTask, _super);
  95401. /**
  95402. * Creates a new HDRCubeTextureAssetTask object
  95403. * @param name defines the name of the task
  95404. * @param url defines the location of the file to load
  95405. * @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.
  95406. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95407. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95408. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  95409. * @param reserved Internal use only
  95410. */
  95411. function HDRCubeTextureAssetTask(
  95412. /**
  95413. * Defines the name of the task
  95414. */
  95415. name,
  95416. /**
  95417. * Defines the location of the file to load
  95418. */
  95419. url,
  95420. /**
  95421. * Defines the desired size (the more it increases the longer the generation will be)
  95422. */
  95423. size,
  95424. /**
  95425. * Defines if mipmaps should not be generated (default is false)
  95426. */
  95427. noMipmap,
  95428. /**
  95429. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95430. */
  95431. generateHarmonics,
  95432. /**
  95433. * 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)
  95434. */
  95435. gammaSpace,
  95436. /**
  95437. * Internal Use Only
  95438. */
  95439. reserved) {
  95440. if (noMipmap === void 0) { noMipmap = false; }
  95441. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95442. if (gammaSpace === void 0) { gammaSpace = false; }
  95443. if (reserved === void 0) { reserved = false; }
  95444. var _this = _super.call(this, name) || this;
  95445. _this.name = name;
  95446. _this.url = url;
  95447. _this.size = size;
  95448. _this.noMipmap = noMipmap;
  95449. _this.generateHarmonics = generateHarmonics;
  95450. _this.gammaSpace = gammaSpace;
  95451. _this.reserved = reserved;
  95452. return _this;
  95453. }
  95454. /**
  95455. * Execute the current task
  95456. * @param scene defines the scene where you want your assets to be loaded
  95457. * @param onSuccess is a callback called when the task is successfully executed
  95458. * @param onError is a callback called if an error occurs
  95459. */
  95460. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95461. var onload = function () {
  95462. onSuccess();
  95463. };
  95464. var onerror = function (message, exception) {
  95465. onError(message, exception);
  95466. };
  95467. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95468. };
  95469. return HDRCubeTextureAssetTask;
  95470. }(AbstractAssetTask));
  95471. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95472. /**
  95473. * This class can be used to easily import assets into a scene
  95474. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95475. */
  95476. var AssetsManager = /** @class */ (function () {
  95477. /**
  95478. * Creates a new AssetsManager
  95479. * @param scene defines the scene to work on
  95480. */
  95481. function AssetsManager(scene) {
  95482. this._isLoading = false;
  95483. this._tasks = new Array();
  95484. this._waitingTasksCount = 0;
  95485. this._totalTasksCount = 0;
  95486. /**
  95487. * Observable called when all tasks are processed
  95488. */
  95489. this.onTaskSuccessObservable = new BABYLON.Observable();
  95490. /**
  95491. * Observable called when a task had an error
  95492. */
  95493. this.onTaskErrorObservable = new BABYLON.Observable();
  95494. /**
  95495. * Observable called when a task is successful
  95496. */
  95497. this.onTasksDoneObservable = new BABYLON.Observable();
  95498. /**
  95499. * Observable called when a task is done (whatever the result is)
  95500. */
  95501. this.onProgressObservable = new BABYLON.Observable();
  95502. /**
  95503. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95504. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95505. */
  95506. this.useDefaultLoadingScreen = true;
  95507. this._scene = scene;
  95508. }
  95509. /**
  95510. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95511. * @param taskName defines the name of the new task
  95512. * @param meshesNames defines the name of meshes to load
  95513. * @param rootUrl defines the root url to use to locate files
  95514. * @param sceneFilename defines the filename of the scene file
  95515. * @returns a new {BABYLON.MeshAssetTask} object
  95516. */
  95517. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95518. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95519. this._tasks.push(task);
  95520. return task;
  95521. };
  95522. /**
  95523. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95524. * @param taskName defines the name of the new task
  95525. * @param url defines the url of the file to load
  95526. * @returns a new {BABYLON.TextFileAssetTask} object
  95527. */
  95528. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95529. var task = new TextFileAssetTask(taskName, url);
  95530. this._tasks.push(task);
  95531. return task;
  95532. };
  95533. /**
  95534. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95535. * @param taskName defines the name of the new task
  95536. * @param url defines the url of the file to load
  95537. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95538. */
  95539. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95540. var task = new BinaryFileAssetTask(taskName, url);
  95541. this._tasks.push(task);
  95542. return task;
  95543. };
  95544. /**
  95545. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95546. * @param taskName defines the name of the new task
  95547. * @param url defines the url of the file to load
  95548. * @returns a new {BABYLON.ImageAssetTask} object
  95549. */
  95550. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95551. var task = new ImageAssetTask(taskName, url);
  95552. this._tasks.push(task);
  95553. return task;
  95554. };
  95555. /**
  95556. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95557. * @param taskName defines the name of the new task
  95558. * @param url defines the url of the file to load
  95559. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95560. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95561. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95562. * @returns a new {BABYLON.TextureAssetTask} object
  95563. */
  95564. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95565. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95566. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95567. this._tasks.push(task);
  95568. return task;
  95569. };
  95570. /**
  95571. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95572. * @param taskName defines the name of the new task
  95573. * @param url defines the url of the file to load
  95574. * @param extensions defines the extension to use to load the cube map (can be null)
  95575. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95576. * @param files defines the list of files to load (can be null)
  95577. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95578. */
  95579. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95580. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95581. this._tasks.push(task);
  95582. return task;
  95583. };
  95584. /**
  95585. *
  95586. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95587. * @param taskName defines the name of the new task
  95588. * @param url defines the url of the file to load
  95589. * @param size defines the size you want for the cubemap (can be null)
  95590. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95591. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95592. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  95593. * @param reserved Internal use only
  95594. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95595. */
  95596. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95597. if (noMipmap === void 0) { noMipmap = false; }
  95598. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95599. if (gammaSpace === void 0) { gammaSpace = false; }
  95600. if (reserved === void 0) { reserved = false; }
  95601. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95602. this._tasks.push(task);
  95603. return task;
  95604. };
  95605. /**
  95606. * Remove a task from the assets manager.
  95607. * @param task the task to remove
  95608. */
  95609. AssetsManager.prototype.removeTask = function (task) {
  95610. var index = this._tasks.indexOf(task);
  95611. if (index > -1) {
  95612. this._tasks.splice(index, 1);
  95613. }
  95614. };
  95615. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  95616. this._waitingTasksCount--;
  95617. try {
  95618. if (this.onProgress) {
  95619. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  95620. }
  95621. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  95622. }
  95623. catch (e) {
  95624. BABYLON.Tools.Error("Error running progress callbacks.");
  95625. console.log(e);
  95626. }
  95627. if (this._waitingTasksCount === 0) {
  95628. try {
  95629. if (this.onFinish) {
  95630. this.onFinish(this._tasks);
  95631. }
  95632. // Let's remove successfull tasks
  95633. var currentTasks = this._tasks.slice();
  95634. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  95635. var task = currentTasks_1[_i];
  95636. if (task.taskState === AssetTaskState.DONE) {
  95637. var index = this._tasks.indexOf(task);
  95638. if (index > -1) {
  95639. this._tasks.splice(index, 1);
  95640. }
  95641. }
  95642. }
  95643. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95644. }
  95645. catch (e) {
  95646. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  95647. console.log(e);
  95648. }
  95649. this._isLoading = false;
  95650. this._scene.getEngine().hideLoadingUI();
  95651. }
  95652. };
  95653. AssetsManager.prototype._runTask = function (task) {
  95654. var _this = this;
  95655. var done = function () {
  95656. try {
  95657. if (_this.onTaskSuccess) {
  95658. _this.onTaskSuccess(task);
  95659. }
  95660. _this.onTaskSuccessObservable.notifyObservers(task);
  95661. _this._decreaseWaitingTasksCount(task);
  95662. }
  95663. catch (e) {
  95664. error("Error executing task success callbacks", e);
  95665. }
  95666. };
  95667. var error = function (message, exception) {
  95668. task._setErrorObject(message, exception);
  95669. if (_this.onTaskError) {
  95670. _this.onTaskError(task);
  95671. }
  95672. _this.onTaskErrorObservable.notifyObservers(task);
  95673. _this._decreaseWaitingTasksCount(task);
  95674. };
  95675. task.run(this._scene, done, error);
  95676. };
  95677. /**
  95678. * Reset the {BABYLON.AssetsManager} and remove all tasks
  95679. * @return the current instance of the {BABYLON.AssetsManager}
  95680. */
  95681. AssetsManager.prototype.reset = function () {
  95682. this._isLoading = false;
  95683. this._tasks = new Array();
  95684. return this;
  95685. };
  95686. /**
  95687. * Start the loading process
  95688. * @return the current instance of the {BABYLON.AssetsManager}
  95689. */
  95690. AssetsManager.prototype.load = function () {
  95691. if (this._isLoading) {
  95692. return this;
  95693. }
  95694. this._isLoading = true;
  95695. this._waitingTasksCount = this._tasks.length;
  95696. this._totalTasksCount = this._tasks.length;
  95697. if (this._waitingTasksCount === 0) {
  95698. this._isLoading = false;
  95699. if (this.onFinish) {
  95700. this.onFinish(this._tasks);
  95701. }
  95702. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95703. return this;
  95704. }
  95705. if (this.useDefaultLoadingScreen) {
  95706. this._scene.getEngine().displayLoadingUI();
  95707. }
  95708. for (var index = 0; index < this._tasks.length; index++) {
  95709. var task = this._tasks[index];
  95710. if (task.taskState === AssetTaskState.INIT) {
  95711. this._runTask(task);
  95712. }
  95713. }
  95714. return this;
  95715. };
  95716. return AssetsManager;
  95717. }());
  95718. BABYLON.AssetsManager = AssetsManager;
  95719. })(BABYLON || (BABYLON = {}));
  95720. //# sourceMappingURL=babylon.assetsManager.js.map
  95721. var BABYLON;
  95722. (function (BABYLON) {
  95723. var serializedGeometries = [];
  95724. var serializeGeometry = function (geometry, serializationGeometries) {
  95725. if (serializedGeometries[geometry.id]) {
  95726. return;
  95727. }
  95728. if (geometry.doNotSerialize) {
  95729. return;
  95730. }
  95731. if (geometry instanceof BABYLON.BoxGeometry) {
  95732. serializationGeometries.boxes.push(geometry.serialize());
  95733. }
  95734. else if (geometry instanceof BABYLON.SphereGeometry) {
  95735. serializationGeometries.spheres.push(geometry.serialize());
  95736. }
  95737. else if (geometry instanceof BABYLON.CylinderGeometry) {
  95738. serializationGeometries.cylinders.push(geometry.serialize());
  95739. }
  95740. else if (geometry instanceof BABYLON.TorusGeometry) {
  95741. serializationGeometries.toruses.push(geometry.serialize());
  95742. }
  95743. else if (geometry instanceof BABYLON.GroundGeometry) {
  95744. serializationGeometries.grounds.push(geometry.serialize());
  95745. }
  95746. else if (geometry instanceof BABYLON.Plane) {
  95747. serializationGeometries.planes.push(geometry.serialize());
  95748. }
  95749. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  95750. serializationGeometries.torusKnots.push(geometry.serialize());
  95751. }
  95752. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  95753. throw new Error("Unknown primitive type");
  95754. }
  95755. else {
  95756. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  95757. }
  95758. serializedGeometries[geometry.id] = true;
  95759. };
  95760. var serializeMesh = function (mesh, serializationScene) {
  95761. var serializationObject = {};
  95762. // Geometry
  95763. var geometry = mesh._geometry;
  95764. if (geometry) {
  95765. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  95766. // 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
  95767. serializeGeometry(geometry, serializationScene.geometries);
  95768. }
  95769. }
  95770. // Custom
  95771. if (mesh.serialize) {
  95772. mesh.serialize(serializationObject);
  95773. }
  95774. return serializationObject;
  95775. };
  95776. var finalizeSingleMesh = function (mesh, serializationObject) {
  95777. //only works if the mesh is already loaded
  95778. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95779. //serialize material
  95780. if (mesh.material) {
  95781. if (mesh.material instanceof BABYLON.MultiMaterial) {
  95782. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  95783. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95784. serializationObject.multiMaterials.push(mesh.material.serialize());
  95785. }
  95786. }
  95787. else {
  95788. serializationObject.materials = serializationObject.materials || [];
  95789. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95790. serializationObject.materials.push(mesh.material.serialize());
  95791. }
  95792. }
  95793. }
  95794. //serialize geometry
  95795. var geometry = mesh._geometry;
  95796. if (geometry) {
  95797. if (!serializationObject.geometries) {
  95798. serializationObject.geometries = {};
  95799. serializationObject.geometries.boxes = [];
  95800. serializationObject.geometries.spheres = [];
  95801. serializationObject.geometries.cylinders = [];
  95802. serializationObject.geometries.toruses = [];
  95803. serializationObject.geometries.grounds = [];
  95804. serializationObject.geometries.planes = [];
  95805. serializationObject.geometries.torusKnots = [];
  95806. serializationObject.geometries.vertexData = [];
  95807. }
  95808. serializeGeometry(geometry, serializationObject.geometries);
  95809. }
  95810. // Skeletons
  95811. if (mesh.skeleton) {
  95812. serializationObject.skeletons = serializationObject.skeletons || [];
  95813. serializationObject.skeletons.push(mesh.skeleton.serialize());
  95814. }
  95815. //serialize the actual mesh
  95816. serializationObject.meshes = serializationObject.meshes || [];
  95817. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95818. }
  95819. };
  95820. var SceneSerializer = /** @class */ (function () {
  95821. function SceneSerializer() {
  95822. }
  95823. SceneSerializer.ClearCache = function () {
  95824. serializedGeometries = [];
  95825. };
  95826. SceneSerializer.Serialize = function (scene) {
  95827. var serializationObject = {};
  95828. SceneSerializer.ClearCache();
  95829. // Scene
  95830. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  95831. serializationObject.autoClear = scene.autoClear;
  95832. serializationObject.clearColor = scene.clearColor.asArray();
  95833. serializationObject.ambientColor = scene.ambientColor.asArray();
  95834. serializationObject.gravity = scene.gravity.asArray();
  95835. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  95836. serializationObject.workerCollisions = scene.workerCollisions;
  95837. // Fog
  95838. if (scene.fogMode && scene.fogMode !== 0) {
  95839. serializationObject.fogMode = scene.fogMode;
  95840. serializationObject.fogColor = scene.fogColor.asArray();
  95841. serializationObject.fogStart = scene.fogStart;
  95842. serializationObject.fogEnd = scene.fogEnd;
  95843. serializationObject.fogDensity = scene.fogDensity;
  95844. }
  95845. //Physics
  95846. if (scene.isPhysicsEnabled()) {
  95847. var physicEngine = scene.getPhysicsEngine();
  95848. if (physicEngine) {
  95849. serializationObject.physicsEnabled = true;
  95850. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  95851. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  95852. }
  95853. }
  95854. // Metadata
  95855. if (scene.metadata) {
  95856. serializationObject.metadata = scene.metadata;
  95857. }
  95858. // Morph targets
  95859. serializationObject.morphTargetManagers = [];
  95860. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  95861. var abstractMesh = _a[_i];
  95862. var manager = abstractMesh.morphTargetManager;
  95863. if (manager) {
  95864. serializationObject.morphTargetManagers.push(manager.serialize());
  95865. }
  95866. }
  95867. // Lights
  95868. serializationObject.lights = [];
  95869. var index;
  95870. var light;
  95871. for (index = 0; index < scene.lights.length; index++) {
  95872. light = scene.lights[index];
  95873. if (!light.doNotSerialize) {
  95874. serializationObject.lights.push(light.serialize());
  95875. }
  95876. }
  95877. // Cameras
  95878. serializationObject.cameras = [];
  95879. for (index = 0; index < scene.cameras.length; index++) {
  95880. var camera = scene.cameras[index];
  95881. if (!camera.doNotSerialize) {
  95882. serializationObject.cameras.push(camera.serialize());
  95883. }
  95884. }
  95885. if (scene.activeCamera) {
  95886. serializationObject.activeCameraID = scene.activeCamera.id;
  95887. }
  95888. // Animations
  95889. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  95890. // Materials
  95891. serializationObject.materials = [];
  95892. serializationObject.multiMaterials = [];
  95893. var material;
  95894. for (index = 0; index < scene.materials.length; index++) {
  95895. material = scene.materials[index];
  95896. if (!material.doNotSerialize) {
  95897. serializationObject.materials.push(material.serialize());
  95898. }
  95899. }
  95900. // MultiMaterials
  95901. serializationObject.multiMaterials = [];
  95902. for (index = 0; index < scene.multiMaterials.length; index++) {
  95903. var multiMaterial = scene.multiMaterials[index];
  95904. serializationObject.multiMaterials.push(multiMaterial.serialize());
  95905. }
  95906. // Environment texture
  95907. if (scene.environmentTexture) {
  95908. serializationObject.environmentTexture = scene.environmentTexture.name;
  95909. }
  95910. // Skeletons
  95911. serializationObject.skeletons = [];
  95912. for (index = 0; index < scene.skeletons.length; index++) {
  95913. var skeleton = scene.skeletons[index];
  95914. if (!skeleton.doNotSerialize) {
  95915. serializationObject.skeletons.push(skeleton.serialize());
  95916. }
  95917. }
  95918. // Transform nodes
  95919. serializationObject.transformNodes = [];
  95920. for (index = 0; index < scene.transformNodes.length; index++) {
  95921. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  95922. }
  95923. // Geometries
  95924. serializationObject.geometries = {};
  95925. serializationObject.geometries.boxes = [];
  95926. serializationObject.geometries.spheres = [];
  95927. serializationObject.geometries.cylinders = [];
  95928. serializationObject.geometries.toruses = [];
  95929. serializationObject.geometries.grounds = [];
  95930. serializationObject.geometries.planes = [];
  95931. serializationObject.geometries.torusKnots = [];
  95932. serializationObject.geometries.vertexData = [];
  95933. serializedGeometries = [];
  95934. var geometries = scene.getGeometries();
  95935. for (index = 0; index < geometries.length; index++) {
  95936. var geometry = geometries[index];
  95937. if (geometry.isReady()) {
  95938. serializeGeometry(geometry, serializationObject.geometries);
  95939. }
  95940. }
  95941. // Meshes
  95942. serializationObject.meshes = [];
  95943. for (index = 0; index < scene.meshes.length; index++) {
  95944. var abstractMesh = scene.meshes[index];
  95945. if (abstractMesh instanceof BABYLON.Mesh) {
  95946. var mesh = abstractMesh;
  95947. if (!mesh.doNotSerialize) {
  95948. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95949. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95950. }
  95951. }
  95952. }
  95953. }
  95954. // Particles Systems
  95955. serializationObject.particleSystems = [];
  95956. for (index = 0; index < scene.particleSystems.length; index++) {
  95957. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  95958. }
  95959. // Lens flares
  95960. serializationObject.lensFlareSystems = [];
  95961. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  95962. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  95963. }
  95964. // Shadows
  95965. serializationObject.shadowGenerators = [];
  95966. for (index = 0; index < scene.lights.length; index++) {
  95967. light = scene.lights[index];
  95968. var shadowGenerator = light.getShadowGenerator();
  95969. if (shadowGenerator) {
  95970. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  95971. }
  95972. }
  95973. // Action Manager
  95974. if (scene.actionManager) {
  95975. serializationObject.actions = scene.actionManager.serialize("scene");
  95976. }
  95977. // Audio
  95978. serializationObject.sounds = [];
  95979. for (index = 0; index < scene.soundTracks.length; index++) {
  95980. var soundtrack = scene.soundTracks[index];
  95981. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  95982. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  95983. }
  95984. }
  95985. // Effect layers
  95986. serializationObject.effectLayers = [];
  95987. for (index = 0; index < scene.effectLayers.length; index++) {
  95988. var layer = scene.effectLayers[index];
  95989. if (layer.serialize) {
  95990. serializationObject.effectLayers.push(layer.serialize());
  95991. }
  95992. }
  95993. return serializationObject;
  95994. };
  95995. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  95996. if (withParents === void 0) { withParents = false; }
  95997. if (withChildren === void 0) { withChildren = false; }
  95998. var serializationObject = {};
  95999. SceneSerializer.ClearCache();
  96000. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96001. if (withParents || withChildren) {
  96002. //deliberate for loop! not for each, appended should be processed as well.
  96003. for (var i = 0; i < toSerialize.length; ++i) {
  96004. if (withChildren) {
  96005. toSerialize[i].getDescendants().forEach(function (node) {
  96006. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96007. toSerialize.push(node);
  96008. }
  96009. });
  96010. }
  96011. //make sure the array doesn't contain the object already
  96012. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96013. toSerialize.push(toSerialize[i].parent);
  96014. }
  96015. }
  96016. }
  96017. toSerialize.forEach(function (mesh) {
  96018. finalizeSingleMesh(mesh, serializationObject);
  96019. });
  96020. return serializationObject;
  96021. };
  96022. return SceneSerializer;
  96023. }());
  96024. BABYLON.SceneSerializer = SceneSerializer;
  96025. })(BABYLON || (BABYLON = {}));
  96026. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96027. var BABYLON;
  96028. (function (BABYLON) {
  96029. var ReflectionProbe = /** @class */ (function () {
  96030. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96031. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96032. var _this = this;
  96033. this.name = name;
  96034. this._viewMatrix = BABYLON.Matrix.Identity();
  96035. this._target = BABYLON.Vector3.Zero();
  96036. this._add = BABYLON.Vector3.Zero();
  96037. this._invertYAxis = false;
  96038. this.position = BABYLON.Vector3.Zero();
  96039. this._scene = scene;
  96040. this._scene.reflectionProbes.push(this);
  96041. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96042. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96043. switch (faceIndex) {
  96044. case 0:
  96045. _this._add.copyFromFloats(1, 0, 0);
  96046. break;
  96047. case 1:
  96048. _this._add.copyFromFloats(-1, 0, 0);
  96049. break;
  96050. case 2:
  96051. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96052. break;
  96053. case 3:
  96054. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96055. break;
  96056. case 4:
  96057. _this._add.copyFromFloats(0, 0, 1);
  96058. break;
  96059. case 5:
  96060. _this._add.copyFromFloats(0, 0, -1);
  96061. break;
  96062. }
  96063. if (_this._attachedMesh) {
  96064. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96065. }
  96066. _this.position.addToRef(_this._add, _this._target);
  96067. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96068. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96069. scene._forcedViewPosition = _this.position;
  96070. });
  96071. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96072. scene._forcedViewPosition = null;
  96073. scene.updateTransformMatrix(true);
  96074. });
  96075. if (scene.activeCamera) {
  96076. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96077. }
  96078. }
  96079. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96080. get: function () {
  96081. return this._renderTargetTexture.samples;
  96082. },
  96083. set: function (value) {
  96084. this._renderTargetTexture.samples = value;
  96085. },
  96086. enumerable: true,
  96087. configurable: true
  96088. });
  96089. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96090. get: function () {
  96091. return this._renderTargetTexture.refreshRate;
  96092. },
  96093. set: function (value) {
  96094. this._renderTargetTexture.refreshRate = value;
  96095. },
  96096. enumerable: true,
  96097. configurable: true
  96098. });
  96099. ReflectionProbe.prototype.getScene = function () {
  96100. return this._scene;
  96101. };
  96102. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96103. get: function () {
  96104. return this._renderTargetTexture;
  96105. },
  96106. enumerable: true,
  96107. configurable: true
  96108. });
  96109. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96110. get: function () {
  96111. return this._renderTargetTexture.renderList;
  96112. },
  96113. enumerable: true,
  96114. configurable: true
  96115. });
  96116. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96117. this._attachedMesh = mesh;
  96118. };
  96119. /**
  96120. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96121. *
  96122. * @param renderingGroupId The rendering group id corresponding to its index
  96123. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96124. */
  96125. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96126. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96127. };
  96128. ReflectionProbe.prototype.dispose = function () {
  96129. var index = this._scene.reflectionProbes.indexOf(this);
  96130. if (index !== -1) {
  96131. // Remove from the scene if found
  96132. this._scene.reflectionProbes.splice(index, 1);
  96133. }
  96134. if (this._renderTargetTexture) {
  96135. this._renderTargetTexture.dispose();
  96136. this._renderTargetTexture = null;
  96137. }
  96138. };
  96139. return ReflectionProbe;
  96140. }());
  96141. BABYLON.ReflectionProbe = ReflectionProbe;
  96142. })(BABYLON || (BABYLON = {}));
  96143. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96144. var BABYLON;
  96145. (function (BABYLON) {
  96146. var Layer = /** @class */ (function () {
  96147. function Layer(name, imgUrl, scene, isBackground, color) {
  96148. this.name = name;
  96149. this.scale = new BABYLON.Vector2(1, 1);
  96150. this.offset = new BABYLON.Vector2(0, 0);
  96151. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96152. this.layerMask = 0x0FFFFFFF;
  96153. this._vertexBuffers = {};
  96154. // Events
  96155. /**
  96156. * An event triggered when the layer is disposed.
  96157. */
  96158. this.onDisposeObservable = new BABYLON.Observable();
  96159. /**
  96160. * An event triggered before rendering the scene
  96161. */
  96162. this.onBeforeRenderObservable = new BABYLON.Observable();
  96163. /**
  96164. * An event triggered after rendering the scene
  96165. */
  96166. this.onAfterRenderObservable = new BABYLON.Observable();
  96167. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96168. this.isBackground = isBackground === undefined ? true : isBackground;
  96169. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96170. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96171. this._scene.layers.push(this);
  96172. var engine = this._scene.getEngine();
  96173. // VBO
  96174. var vertices = [];
  96175. vertices.push(1, 1);
  96176. vertices.push(-1, 1);
  96177. vertices.push(-1, -1);
  96178. vertices.push(1, -1);
  96179. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96180. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96181. this._createIndexBuffer();
  96182. // Effects
  96183. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96184. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96185. }
  96186. Object.defineProperty(Layer.prototype, "onDispose", {
  96187. set: function (callback) {
  96188. if (this._onDisposeObserver) {
  96189. this.onDisposeObservable.remove(this._onDisposeObserver);
  96190. }
  96191. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96192. },
  96193. enumerable: true,
  96194. configurable: true
  96195. });
  96196. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96197. set: function (callback) {
  96198. if (this._onBeforeRenderObserver) {
  96199. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96200. }
  96201. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96202. },
  96203. enumerable: true,
  96204. configurable: true
  96205. });
  96206. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96207. set: function (callback) {
  96208. if (this._onAfterRenderObserver) {
  96209. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96210. }
  96211. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96212. },
  96213. enumerable: true,
  96214. configurable: true
  96215. });
  96216. Layer.prototype._createIndexBuffer = function () {
  96217. var engine = this._scene.getEngine();
  96218. // Indices
  96219. var indices = [];
  96220. indices.push(0);
  96221. indices.push(1);
  96222. indices.push(2);
  96223. indices.push(0);
  96224. indices.push(2);
  96225. indices.push(3);
  96226. this._indexBuffer = engine.createIndexBuffer(indices);
  96227. };
  96228. Layer.prototype._rebuild = function () {
  96229. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96230. if (vb) {
  96231. vb._rebuild();
  96232. }
  96233. this._createIndexBuffer();
  96234. };
  96235. Layer.prototype.render = function () {
  96236. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96237. // Check
  96238. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96239. return;
  96240. var engine = this._scene.getEngine();
  96241. this.onBeforeRenderObservable.notifyObservers(this);
  96242. // Render
  96243. engine.enableEffect(currentEffect);
  96244. engine.setState(false);
  96245. // Texture
  96246. currentEffect.setTexture("textureSampler", this.texture);
  96247. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96248. // Color
  96249. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96250. // Scale / offset
  96251. currentEffect.setVector2("offset", this.offset);
  96252. currentEffect.setVector2("scale", this.scale);
  96253. // VBOs
  96254. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96255. // Draw order
  96256. if (!this.alphaTest) {
  96257. engine.setAlphaMode(this.alphaBlendingMode);
  96258. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96259. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96260. }
  96261. else {
  96262. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96263. }
  96264. this.onAfterRenderObservable.notifyObservers(this);
  96265. };
  96266. Layer.prototype.dispose = function () {
  96267. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96268. if (vertexBuffer) {
  96269. vertexBuffer.dispose();
  96270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96271. }
  96272. if (this._indexBuffer) {
  96273. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96274. this._indexBuffer = null;
  96275. }
  96276. if (this.texture) {
  96277. this.texture.dispose();
  96278. this.texture = null;
  96279. }
  96280. // Remove from scene
  96281. var index = this._scene.layers.indexOf(this);
  96282. this._scene.layers.splice(index, 1);
  96283. // Callback
  96284. this.onDisposeObservable.notifyObservers(this);
  96285. this.onDisposeObservable.clear();
  96286. this.onAfterRenderObservable.clear();
  96287. this.onBeforeRenderObservable.clear();
  96288. };
  96289. return Layer;
  96290. }());
  96291. BABYLON.Layer = Layer;
  96292. })(BABYLON || (BABYLON = {}));
  96293. //# sourceMappingURL=babylon.layer.js.map
  96294. var BABYLON;
  96295. (function (BABYLON) {
  96296. var TextureTools = /** @class */ (function () {
  96297. function TextureTools() {
  96298. }
  96299. /**
  96300. * Uses the GPU to create a copy texture rescaled at a given size
  96301. * @param texture Texture to copy from
  96302. * @param width Desired width
  96303. * @param height Desired height
  96304. * @return Generated texture
  96305. */
  96306. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96307. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96308. var scene = texture.getScene();
  96309. var engine = scene.getEngine();
  96310. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96311. rtt.wrapU = texture.wrapU;
  96312. rtt.wrapV = texture.wrapV;
  96313. rtt.uOffset = texture.uOffset;
  96314. rtt.vOffset = texture.vOffset;
  96315. rtt.uScale = texture.uScale;
  96316. rtt.vScale = texture.vScale;
  96317. rtt.uAng = texture.uAng;
  96318. rtt.vAng = texture.vAng;
  96319. rtt.wAng = texture.wAng;
  96320. rtt.coordinatesIndex = texture.coordinatesIndex;
  96321. rtt.level = texture.level;
  96322. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96323. rtt._texture.isReady = false;
  96324. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96325. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96326. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96327. passPostProcess.getEffect().executeWhenCompiled(function () {
  96328. passPostProcess.onApply = function (effect) {
  96329. effect.setTexture("textureSampler", texture);
  96330. };
  96331. var internalTexture = rtt.getInternalTexture();
  96332. if (internalTexture) {
  96333. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96334. engine.unBindFramebuffer(internalTexture);
  96335. rtt.disposeFramebufferObjects();
  96336. passPostProcess.dispose();
  96337. internalTexture.isReady = true;
  96338. }
  96339. });
  96340. return rtt;
  96341. };
  96342. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96343. if (!scene._environmentBRDFTexture) {
  96344. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96345. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96346. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96347. scene._environmentBRDFTexture = texture;
  96348. }
  96349. return scene._environmentBRDFTexture;
  96350. };
  96351. 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=";
  96352. return TextureTools;
  96353. }());
  96354. BABYLON.TextureTools = TextureTools;
  96355. })(BABYLON || (BABYLON = {}));
  96356. //# sourceMappingURL=babylon.textureTools.js.map
  96357. var BABYLON;
  96358. (function (BABYLON) {
  96359. var FramingBehavior = /** @class */ (function () {
  96360. function FramingBehavior() {
  96361. this._mode = FramingBehavior.FitFrustumSidesMode;
  96362. this._radiusScale = 1.0;
  96363. this._positionScale = 0.5;
  96364. this._defaultElevation = 0.3;
  96365. this._elevationReturnTime = 1500;
  96366. this._elevationReturnWaitTime = 1000;
  96367. this._zoomStopsAnimation = false;
  96368. this._framingTime = 1500;
  96369. this._isPointerDown = false;
  96370. this._lastInteractionTime = -Infinity;
  96371. // Framing control
  96372. this._animatables = new Array();
  96373. this._betaIsAnimating = false;
  96374. }
  96375. Object.defineProperty(FramingBehavior.prototype, "name", {
  96376. get: function () {
  96377. return "Framing";
  96378. },
  96379. enumerable: true,
  96380. configurable: true
  96381. });
  96382. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96383. /**
  96384. * Gets current mode used by the behavior.
  96385. */
  96386. get: function () {
  96387. return this._mode;
  96388. },
  96389. /**
  96390. * Sets the current mode used by the behavior
  96391. */
  96392. set: function (mode) {
  96393. this._mode = mode;
  96394. },
  96395. enumerable: true,
  96396. configurable: true
  96397. });
  96398. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96399. /**
  96400. * Gets the scale applied to the radius
  96401. */
  96402. get: function () {
  96403. return this._radiusScale;
  96404. },
  96405. /**
  96406. * Sets the scale applied to the radius (1 by default)
  96407. */
  96408. set: function (radius) {
  96409. this._radiusScale = radius;
  96410. },
  96411. enumerable: true,
  96412. configurable: true
  96413. });
  96414. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96415. /**
  96416. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96417. */
  96418. get: function () {
  96419. return this._positionScale;
  96420. },
  96421. /**
  96422. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96423. */
  96424. set: function (scale) {
  96425. this._positionScale = scale;
  96426. },
  96427. enumerable: true,
  96428. configurable: true
  96429. });
  96430. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96431. /**
  96432. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96433. * behaviour is triggered, in radians.
  96434. */
  96435. get: function () {
  96436. return this._defaultElevation;
  96437. },
  96438. /**
  96439. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96440. * behaviour is triggered, in radians.
  96441. */
  96442. set: function (elevation) {
  96443. this._defaultElevation = elevation;
  96444. },
  96445. enumerable: true,
  96446. configurable: true
  96447. });
  96448. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96449. /**
  96450. * Gets the time (in milliseconds) taken to return to the default beta position.
  96451. * Negative value indicates camera should not return to default.
  96452. */
  96453. get: function () {
  96454. return this._elevationReturnTime;
  96455. },
  96456. /**
  96457. * Sets the time (in milliseconds) taken to return to the default beta position.
  96458. * Negative value indicates camera should not return to default.
  96459. */
  96460. set: function (speed) {
  96461. this._elevationReturnTime = speed;
  96462. },
  96463. enumerable: true,
  96464. configurable: true
  96465. });
  96466. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96467. /**
  96468. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96469. */
  96470. get: function () {
  96471. return this._elevationReturnWaitTime;
  96472. },
  96473. /**
  96474. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96475. */
  96476. set: function (time) {
  96477. this._elevationReturnWaitTime = time;
  96478. },
  96479. enumerable: true,
  96480. configurable: true
  96481. });
  96482. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96483. /**
  96484. * Gets the flag that indicates if user zooming should stop animation.
  96485. */
  96486. get: function () {
  96487. return this._zoomStopsAnimation;
  96488. },
  96489. /**
  96490. * Sets the flag that indicates if user zooming should stop animation.
  96491. */
  96492. set: function (flag) {
  96493. this._zoomStopsAnimation = flag;
  96494. },
  96495. enumerable: true,
  96496. configurable: true
  96497. });
  96498. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96499. /**
  96500. * Gets the transition time when framing the mesh, in milliseconds
  96501. */
  96502. get: function () {
  96503. return this._framingTime;
  96504. },
  96505. /**
  96506. * Sets the transition time when framing the mesh, in milliseconds
  96507. */
  96508. set: function (time) {
  96509. this._framingTime = time;
  96510. },
  96511. enumerable: true,
  96512. configurable: true
  96513. });
  96514. FramingBehavior.prototype.init = function () {
  96515. // Do notihng
  96516. };
  96517. FramingBehavior.prototype.attach = function (camera) {
  96518. var _this = this;
  96519. this._attachedCamera = camera;
  96520. var scene = this._attachedCamera.getScene();
  96521. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96522. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96523. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96524. _this._isPointerDown = true;
  96525. return;
  96526. }
  96527. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96528. _this._isPointerDown = false;
  96529. }
  96530. });
  96531. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96532. if (mesh) {
  96533. _this.zoomOnMesh(mesh);
  96534. }
  96535. });
  96536. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96537. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96538. _this._applyUserInteraction();
  96539. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96540. // back to the default position after a given timeout
  96541. _this._maintainCameraAboveGround();
  96542. });
  96543. };
  96544. FramingBehavior.prototype.detach = function () {
  96545. if (!this._attachedCamera) {
  96546. return;
  96547. }
  96548. var scene = this._attachedCamera.getScene();
  96549. if (this._onPrePointerObservableObserver) {
  96550. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96551. }
  96552. if (this._onAfterCheckInputsObserver) {
  96553. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96554. }
  96555. if (this._onMeshTargetChangedObserver) {
  96556. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96557. }
  96558. this._attachedCamera = null;
  96559. };
  96560. /**
  96561. * Targets the given mesh and updates zoom level accordingly.
  96562. * @param mesh The mesh to target.
  96563. * @param radius Optional. If a cached radius position already exists, overrides default.
  96564. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96565. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96566. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96567. */
  96568. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96569. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96570. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96571. mesh.computeWorldMatrix(true);
  96572. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96573. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96574. };
  96575. /**
  96576. * Targets the given mesh with its children and updates zoom level accordingly.
  96577. * @param mesh The mesh to target.
  96578. * @param radius Optional. If a cached radius position already exists, overrides default.
  96579. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96580. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96581. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96582. */
  96583. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96584. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96585. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96586. mesh.computeWorldMatrix(true);
  96587. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96588. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96589. };
  96590. /**
  96591. * Targets the given meshes with their children and updates zoom level accordingly.
  96592. * @param meshes The mesh to target.
  96593. * @param radius Optional. If a cached radius position already exists, overrides default.
  96594. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96595. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96596. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96597. */
  96598. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96599. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96600. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96601. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96602. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96603. for (var i = 0; i < meshes.length; i++) {
  96604. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96605. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96606. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96607. }
  96608. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96609. };
  96610. /**
  96611. * Targets the given mesh and updates zoom level accordingly.
  96612. * @param mesh The mesh to target.
  96613. * @param radius Optional. If a cached radius position already exists, overrides default.
  96614. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96615. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96616. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96617. */
  96618. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  96619. var _this = this;
  96620. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96621. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96622. var zoomTarget;
  96623. if (!this._attachedCamera) {
  96624. return;
  96625. }
  96626. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  96627. var bottom = minimumWorld.y;
  96628. var top = maximumWorld.y;
  96629. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  96630. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  96631. if (focusOnOriginXZ) {
  96632. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  96633. }
  96634. else {
  96635. var centerWorld = minimumWorld.add(radiusWorld);
  96636. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  96637. }
  96638. if (!this._vectorTransition) {
  96639. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  96640. }
  96641. this._betaIsAnimating = true;
  96642. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  96643. if (animatable) {
  96644. this._animatables.push(animatable);
  96645. }
  96646. // sets the radius and lower radius bounds
  96647. // Small delta ensures camera is not always at lower zoom limit.
  96648. var radius = 0;
  96649. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  96650. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96651. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  96652. radius = position;
  96653. }
  96654. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96655. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96656. if (this._attachedCamera.lowerRadiusLimit === null) {
  96657. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  96658. }
  96659. }
  96660. // Set sensibilities
  96661. var extend = maximumWorld.subtract(minimumWorld).length();
  96662. this._attachedCamera.panningSensibility = 5000 / extend;
  96663. this._attachedCamera.wheelPrecision = 100 / radius;
  96664. // transition to new radius
  96665. if (!this._radiusTransition) {
  96666. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96667. }
  96668. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  96669. _this.stopAllAnimations();
  96670. if (onAnimationEnd) {
  96671. onAnimationEnd();
  96672. }
  96673. if (_this._attachedCamera) {
  96674. _this._attachedCamera.storeState();
  96675. }
  96676. });
  96677. if (animatable) {
  96678. this._animatables.push(animatable);
  96679. }
  96680. };
  96681. /**
  96682. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  96683. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  96684. * frustum width.
  96685. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  96686. * to fully enclose the mesh in the viewing frustum.
  96687. */
  96688. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  96689. var size = maximumWorld.subtract(minimumWorld);
  96690. var boxVectorGlobalDiagonal = size.length();
  96691. var frustumSlope = this._getFrustumSlope();
  96692. // Formula for setting distance
  96693. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  96694. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  96695. // Horizon distance
  96696. var radius = radiusWithoutFraming * this._radiusScale;
  96697. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  96698. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  96699. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  96700. var camera = this._attachedCamera;
  96701. if (!camera) {
  96702. return 0;
  96703. }
  96704. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96705. // Don't exceed the requested limit
  96706. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  96707. }
  96708. // Don't exceed the upper radius limit
  96709. if (camera.upperRadiusLimit) {
  96710. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  96711. }
  96712. return distance;
  96713. };
  96714. /**
  96715. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  96716. * is automatically returned to its default position (expected to be above ground plane).
  96717. */
  96718. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  96719. var _this = this;
  96720. if (this._elevationReturnTime < 0) {
  96721. return;
  96722. }
  96723. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  96724. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  96725. var limitBeta = Math.PI * 0.5;
  96726. // Bring the camera back up if below the ground plane
  96727. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  96728. this._betaIsAnimating = true;
  96729. //Transition to new position
  96730. this.stopAllAnimations();
  96731. if (!this._betaTransition) {
  96732. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96733. }
  96734. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  96735. _this._clearAnimationLocks();
  96736. _this.stopAllAnimations();
  96737. });
  96738. if (animatabe) {
  96739. this._animatables.push(animatabe);
  96740. }
  96741. }
  96742. };
  96743. /**
  96744. * Returns the frustum slope based on the canvas ratio and camera FOV
  96745. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  96746. */
  96747. FramingBehavior.prototype._getFrustumSlope = function () {
  96748. // Calculate the viewport ratio
  96749. // Aspect Ratio is Height/Width.
  96750. var camera = this._attachedCamera;
  96751. if (!camera) {
  96752. return BABYLON.Vector2.Zero();
  96753. }
  96754. var engine = camera.getScene().getEngine();
  96755. var aspectRatio = engine.getAspectRatio(camera);
  96756. // Camera FOV is the vertical field of view (top-bottom) in radians.
  96757. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  96758. var frustumSlopeY = Math.tan(camera.fov / 2);
  96759. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  96760. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  96761. // along the forward vector.
  96762. var frustumSlopeX = frustumSlopeY * aspectRatio;
  96763. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  96764. };
  96765. /**
  96766. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  96767. */
  96768. FramingBehavior.prototype._clearAnimationLocks = function () {
  96769. this._betaIsAnimating = false;
  96770. };
  96771. /**
  96772. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96773. */
  96774. FramingBehavior.prototype._applyUserInteraction = function () {
  96775. if (this.isUserIsMoving) {
  96776. this._lastInteractionTime = BABYLON.Tools.Now;
  96777. this.stopAllAnimations();
  96778. this._clearAnimationLocks();
  96779. }
  96780. };
  96781. /**
  96782. * Stops and removes all animations that have been applied to the camera
  96783. */
  96784. FramingBehavior.prototype.stopAllAnimations = function () {
  96785. if (this._attachedCamera) {
  96786. this._attachedCamera.animations = [];
  96787. }
  96788. while (this._animatables.length) {
  96789. if (this._animatables[0]) {
  96790. this._animatables[0].onAnimationEnd = null;
  96791. this._animatables[0].stop();
  96792. }
  96793. this._animatables.shift();
  96794. }
  96795. };
  96796. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  96797. /**
  96798. * Gets a value indicating if the user is moving the camera
  96799. */
  96800. get: function () {
  96801. if (!this._attachedCamera) {
  96802. return false;
  96803. }
  96804. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96805. this._attachedCamera.inertialBetaOffset !== 0 ||
  96806. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96807. this._attachedCamera.inertialPanningX !== 0 ||
  96808. this._attachedCamera.inertialPanningY !== 0 ||
  96809. this._isPointerDown;
  96810. },
  96811. enumerable: true,
  96812. configurable: true
  96813. });
  96814. /**
  96815. * The easing function used by animations
  96816. */
  96817. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  96818. /**
  96819. * The easing mode used by animations
  96820. */
  96821. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  96822. // Statics
  96823. /**
  96824. * The camera can move all the way towards the mesh.
  96825. */
  96826. FramingBehavior.IgnoreBoundsSizeMode = 0;
  96827. /**
  96828. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  96829. */
  96830. FramingBehavior.FitFrustumSidesMode = 1;
  96831. return FramingBehavior;
  96832. }());
  96833. BABYLON.FramingBehavior = FramingBehavior;
  96834. })(BABYLON || (BABYLON = {}));
  96835. //# sourceMappingURL=babylon.framingBehavior.js.map
  96836. var BABYLON;
  96837. (function (BABYLON) {
  96838. /**
  96839. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  96840. */
  96841. var BouncingBehavior = /** @class */ (function () {
  96842. function BouncingBehavior() {
  96843. /**
  96844. * The duration of the animation, in milliseconds
  96845. */
  96846. this.transitionDuration = 450;
  96847. /**
  96848. * Length of the distance animated by the transition when lower radius is reached
  96849. */
  96850. this.lowerRadiusTransitionRange = 2;
  96851. /**
  96852. * Length of the distance animated by the transition when upper radius is reached
  96853. */
  96854. this.upperRadiusTransitionRange = -2;
  96855. this._autoTransitionRange = false;
  96856. // Animations
  96857. this._radiusIsAnimating = false;
  96858. this._radiusBounceTransition = null;
  96859. this._animatables = new Array();
  96860. }
  96861. Object.defineProperty(BouncingBehavior.prototype, "name", {
  96862. get: function () {
  96863. return "Bouncing";
  96864. },
  96865. enumerable: true,
  96866. configurable: true
  96867. });
  96868. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  96869. /**
  96870. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96871. */
  96872. get: function () {
  96873. return this._autoTransitionRange;
  96874. },
  96875. /**
  96876. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96877. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  96878. */
  96879. set: function (value) {
  96880. var _this = this;
  96881. if (this._autoTransitionRange === value) {
  96882. return;
  96883. }
  96884. this._autoTransitionRange = value;
  96885. var camera = this._attachedCamera;
  96886. if (!camera) {
  96887. return;
  96888. }
  96889. if (value) {
  96890. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96891. if (!mesh) {
  96892. return;
  96893. }
  96894. mesh.computeWorldMatrix(true);
  96895. var diagonal = mesh.getBoundingInfo().diagonalLength;
  96896. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  96897. _this.upperRadiusTransitionRange = diagonal * 0.05;
  96898. });
  96899. }
  96900. else if (this._onMeshTargetChangedObserver) {
  96901. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96902. }
  96903. },
  96904. enumerable: true,
  96905. configurable: true
  96906. });
  96907. BouncingBehavior.prototype.init = function () {
  96908. // Do notihng
  96909. };
  96910. BouncingBehavior.prototype.attach = function (camera) {
  96911. var _this = this;
  96912. this._attachedCamera = camera;
  96913. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96914. if (!_this._attachedCamera) {
  96915. return;
  96916. }
  96917. // Add the bounce animation to the lower radius limit
  96918. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  96919. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  96920. }
  96921. // Add the bounce animation to the upper radius limit
  96922. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  96923. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  96924. }
  96925. });
  96926. };
  96927. BouncingBehavior.prototype.detach = function () {
  96928. if (!this._attachedCamera) {
  96929. return;
  96930. }
  96931. if (this._onAfterCheckInputsObserver) {
  96932. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96933. }
  96934. if (this._onMeshTargetChangedObserver) {
  96935. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96936. }
  96937. this._attachedCamera = null;
  96938. };
  96939. /**
  96940. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  96941. * @param radiusLimit The limit to check against.
  96942. * @return Bool to indicate if at limit.
  96943. */
  96944. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  96945. if (!this._attachedCamera) {
  96946. return false;
  96947. }
  96948. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  96949. return true;
  96950. }
  96951. return false;
  96952. };
  96953. /**
  96954. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  96955. * @param radiusDelta The delta by which to animate to. Can be negative.
  96956. */
  96957. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  96958. var _this = this;
  96959. if (!this._attachedCamera) {
  96960. return;
  96961. }
  96962. if (!this._radiusBounceTransition) {
  96963. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  96964. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  96965. }
  96966. // Prevent zoom until bounce has completed
  96967. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  96968. this._attachedCamera.wheelPrecision = Infinity;
  96969. this._attachedCamera.inertialRadiusOffset = 0;
  96970. // Animate to the radius limit
  96971. this.stopAllAnimations();
  96972. this._radiusIsAnimating = true;
  96973. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  96974. if (animatable) {
  96975. this._animatables.push(animatable);
  96976. }
  96977. };
  96978. /**
  96979. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  96980. */
  96981. BouncingBehavior.prototype._clearAnimationLocks = function () {
  96982. this._radiusIsAnimating = false;
  96983. if (this._attachedCamera) {
  96984. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  96985. }
  96986. };
  96987. /**
  96988. * Stops and removes all animations that have been applied to the camera
  96989. */
  96990. BouncingBehavior.prototype.stopAllAnimations = function () {
  96991. if (this._attachedCamera) {
  96992. this._attachedCamera.animations = [];
  96993. }
  96994. while (this._animatables.length) {
  96995. this._animatables[0].onAnimationEnd = null;
  96996. this._animatables[0].stop();
  96997. this._animatables.shift();
  96998. }
  96999. };
  97000. /**
  97001. * The easing function used by animations
  97002. */
  97003. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97004. /**
  97005. * The easing mode used by animations
  97006. */
  97007. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97008. return BouncingBehavior;
  97009. }());
  97010. BABYLON.BouncingBehavior = BouncingBehavior;
  97011. })(BABYLON || (BABYLON = {}));
  97012. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97013. var BABYLON;
  97014. (function (BABYLON) {
  97015. var AutoRotationBehavior = /** @class */ (function () {
  97016. function AutoRotationBehavior() {
  97017. this._zoomStopsAnimation = false;
  97018. this._idleRotationSpeed = 0.05;
  97019. this._idleRotationWaitTime = 2000;
  97020. this._idleRotationSpinupTime = 2000;
  97021. this._isPointerDown = false;
  97022. this._lastFrameTime = null;
  97023. this._lastInteractionTime = -Infinity;
  97024. this._cameraRotationSpeed = 0;
  97025. this._lastFrameRadius = 0;
  97026. }
  97027. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97028. get: function () {
  97029. return "AutoRotation";
  97030. },
  97031. enumerable: true,
  97032. configurable: true
  97033. });
  97034. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97035. /**
  97036. * Gets the flag that indicates if user zooming should stop animation.
  97037. */
  97038. get: function () {
  97039. return this._zoomStopsAnimation;
  97040. },
  97041. /**
  97042. * Sets the flag that indicates if user zooming should stop animation.
  97043. */
  97044. set: function (flag) {
  97045. this._zoomStopsAnimation = flag;
  97046. },
  97047. enumerable: true,
  97048. configurable: true
  97049. });
  97050. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97051. /**
  97052. * Gets the default speed at which the camera rotates around the model.
  97053. */
  97054. get: function () {
  97055. return this._idleRotationSpeed;
  97056. },
  97057. /**
  97058. * Sets the default speed at which the camera rotates around the model.
  97059. */
  97060. set: function (speed) {
  97061. this._idleRotationSpeed = speed;
  97062. },
  97063. enumerable: true,
  97064. configurable: true
  97065. });
  97066. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97067. /**
  97068. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97069. */
  97070. get: function () {
  97071. return this._idleRotationWaitTime;
  97072. },
  97073. /**
  97074. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97075. */
  97076. set: function (time) {
  97077. this._idleRotationWaitTime = time;
  97078. },
  97079. enumerable: true,
  97080. configurable: true
  97081. });
  97082. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97083. /**
  97084. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97085. */
  97086. get: function () {
  97087. return this._idleRotationSpinupTime;
  97088. },
  97089. /**
  97090. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97091. */
  97092. set: function (time) {
  97093. this._idleRotationSpinupTime = time;
  97094. },
  97095. enumerable: true,
  97096. configurable: true
  97097. });
  97098. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97099. /**
  97100. * Gets a value indicating if the camera is currently rotating because of this behavior
  97101. */
  97102. get: function () {
  97103. return Math.abs(this._cameraRotationSpeed) > 0;
  97104. },
  97105. enumerable: true,
  97106. configurable: true
  97107. });
  97108. AutoRotationBehavior.prototype.init = function () {
  97109. // Do notihng
  97110. };
  97111. AutoRotationBehavior.prototype.attach = function (camera) {
  97112. var _this = this;
  97113. this._attachedCamera = camera;
  97114. var scene = this._attachedCamera.getScene();
  97115. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97116. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97117. _this._isPointerDown = true;
  97118. return;
  97119. }
  97120. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97121. _this._isPointerDown = false;
  97122. }
  97123. });
  97124. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97125. var now = BABYLON.Tools.Now;
  97126. var dt = 0;
  97127. if (_this._lastFrameTime != null) {
  97128. dt = now - _this._lastFrameTime;
  97129. }
  97130. _this._lastFrameTime = now;
  97131. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97132. _this._applyUserInteraction();
  97133. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97134. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97135. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97136. // Step camera rotation by rotation speed
  97137. if (_this._attachedCamera) {
  97138. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97139. }
  97140. });
  97141. };
  97142. AutoRotationBehavior.prototype.detach = function () {
  97143. if (!this._attachedCamera) {
  97144. return;
  97145. }
  97146. var scene = this._attachedCamera.getScene();
  97147. if (this._onPrePointerObservableObserver) {
  97148. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97149. }
  97150. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97151. this._attachedCamera = null;
  97152. };
  97153. /**
  97154. * Returns true if user is scrolling.
  97155. * @return true if user is scrolling.
  97156. */
  97157. AutoRotationBehavior.prototype._userIsZooming = function () {
  97158. if (!this._attachedCamera) {
  97159. return false;
  97160. }
  97161. return this._attachedCamera.inertialRadiusOffset !== 0;
  97162. };
  97163. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97164. if (!this._attachedCamera) {
  97165. return false;
  97166. }
  97167. var zoomHasHitLimit = false;
  97168. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97169. zoomHasHitLimit = true;
  97170. }
  97171. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97172. this._lastFrameRadius = this._attachedCamera.radius;
  97173. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97174. };
  97175. /**
  97176. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97177. */
  97178. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97179. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97180. this._lastInteractionTime = BABYLON.Tools.Now;
  97181. }
  97182. };
  97183. // Tools
  97184. AutoRotationBehavior.prototype._userIsMoving = function () {
  97185. if (!this._attachedCamera) {
  97186. return false;
  97187. }
  97188. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97189. this._attachedCamera.inertialBetaOffset !== 0 ||
  97190. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97191. this._attachedCamera.inertialPanningX !== 0 ||
  97192. this._attachedCamera.inertialPanningY !== 0 ||
  97193. this._isPointerDown;
  97194. };
  97195. return AutoRotationBehavior;
  97196. }());
  97197. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97198. })(BABYLON || (BABYLON = {}));
  97199. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97200. var BABYLON;
  97201. (function (BABYLON) {
  97202. var NullEngineOptions = /** @class */ (function () {
  97203. function NullEngineOptions() {
  97204. this.renderWidth = 512;
  97205. this.renderHeight = 256;
  97206. this.textureSize = 512;
  97207. this.deterministicLockstep = false;
  97208. this.lockstepMaxSteps = 4;
  97209. }
  97210. return NullEngineOptions;
  97211. }());
  97212. BABYLON.NullEngineOptions = NullEngineOptions;
  97213. /**
  97214. * The null engine class provides support for headless version of babylon.js.
  97215. * This can be used in server side scenario or for testing purposes
  97216. */
  97217. var NullEngine = /** @class */ (function (_super) {
  97218. __extends(NullEngine, _super);
  97219. function NullEngine(options) {
  97220. if (options === void 0) { options = new NullEngineOptions(); }
  97221. var _this = _super.call(this, null) || this;
  97222. if (options.deterministicLockstep === undefined) {
  97223. options.deterministicLockstep = false;
  97224. }
  97225. if (options.lockstepMaxSteps === undefined) {
  97226. options.lockstepMaxSteps = 4;
  97227. }
  97228. _this._options = options;
  97229. // Init caps
  97230. // We consider we are on a webgl1 capable device
  97231. _this._caps = new BABYLON.EngineCapabilities();
  97232. _this._caps.maxTexturesImageUnits = 16;
  97233. _this._caps.maxVertexTextureImageUnits = 16;
  97234. _this._caps.maxTextureSize = 512;
  97235. _this._caps.maxCubemapTextureSize = 512;
  97236. _this._caps.maxRenderTextureSize = 512;
  97237. _this._caps.maxVertexAttribs = 16;
  97238. _this._caps.maxVaryingVectors = 16;
  97239. _this._caps.maxFragmentUniformVectors = 16;
  97240. _this._caps.maxVertexUniformVectors = 16;
  97241. // Extensions
  97242. _this._caps.standardDerivatives = false;
  97243. _this._caps.astc = null;
  97244. _this._caps.s3tc = null;
  97245. _this._caps.pvrtc = null;
  97246. _this._caps.etc1 = null;
  97247. _this._caps.etc2 = null;
  97248. _this._caps.textureAnisotropicFilterExtension = null;
  97249. _this._caps.maxAnisotropy = 0;
  97250. _this._caps.uintIndices = false;
  97251. _this._caps.fragmentDepthSupported = false;
  97252. _this._caps.highPrecisionShaderSupported = true;
  97253. _this._caps.colorBufferFloat = false;
  97254. _this._caps.textureFloat = false;
  97255. _this._caps.textureFloatLinearFiltering = false;
  97256. _this._caps.textureFloatRender = false;
  97257. _this._caps.textureHalfFloat = false;
  97258. _this._caps.textureHalfFloatLinearFiltering = false;
  97259. _this._caps.textureHalfFloatRender = false;
  97260. _this._caps.textureLOD = false;
  97261. _this._caps.drawBuffersExtension = false;
  97262. _this._caps.depthTextureExtension = false;
  97263. _this._caps.vertexArrayObject = false;
  97264. _this._caps.instancedArrays = false;
  97265. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97266. // Wrappers
  97267. if (typeof URL === "undefined") {
  97268. URL = {
  97269. createObjectURL: function () { },
  97270. revokeObjectURL: function () { }
  97271. };
  97272. }
  97273. if (typeof Blob === "undefined") {
  97274. Blob = function () { };
  97275. }
  97276. return _this;
  97277. }
  97278. NullEngine.prototype.isDeterministicLockStep = function () {
  97279. return this._options.deterministicLockstep;
  97280. };
  97281. NullEngine.prototype.getLockstepMaxSteps = function () {
  97282. return this._options.lockstepMaxSteps;
  97283. };
  97284. NullEngine.prototype.getHardwareScalingLevel = function () {
  97285. return 1.0;
  97286. };
  97287. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97288. return {
  97289. capacity: 0,
  97290. references: 1,
  97291. is32Bits: false
  97292. };
  97293. };
  97294. NullEngine.prototype.createIndexBuffer = function (indices) {
  97295. return {
  97296. capacity: 0,
  97297. references: 1,
  97298. is32Bits: false
  97299. };
  97300. };
  97301. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97302. if (stencil === void 0) { stencil = false; }
  97303. };
  97304. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97305. if (useScreen === void 0) { useScreen = false; }
  97306. if (!useScreen && this._currentRenderTarget) {
  97307. return this._currentRenderTarget.width;
  97308. }
  97309. return this._options.renderWidth;
  97310. };
  97311. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97312. if (useScreen === void 0) { useScreen = false; }
  97313. if (!useScreen && this._currentRenderTarget) {
  97314. return this._currentRenderTarget.height;
  97315. }
  97316. return this._options.renderHeight;
  97317. };
  97318. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97319. this._cachedViewport = viewport;
  97320. };
  97321. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97322. return {
  97323. transformFeedback: null,
  97324. __SPECTOR_rebuildProgram: null
  97325. };
  97326. };
  97327. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97328. return [];
  97329. };
  97330. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97331. return [];
  97332. };
  97333. NullEngine.prototype.bindSamplers = function (effect) {
  97334. this._currentEffect = null;
  97335. };
  97336. NullEngine.prototype.enableEffect = function (effect) {
  97337. this._currentEffect = effect;
  97338. if (effect.onBind) {
  97339. effect.onBind(effect);
  97340. }
  97341. effect.onBindObservable.notifyObservers(effect);
  97342. };
  97343. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97344. if (zOffset === void 0) { zOffset = 0; }
  97345. if (reverseSide === void 0) { reverseSide = false; }
  97346. };
  97347. NullEngine.prototype.setIntArray = function (uniform, array) {
  97348. };
  97349. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97350. };
  97351. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97352. };
  97353. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97354. };
  97355. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97356. };
  97357. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97358. };
  97359. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97360. };
  97361. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97362. };
  97363. NullEngine.prototype.setArray = function (uniform, array) {
  97364. };
  97365. NullEngine.prototype.setArray2 = function (uniform, array) {
  97366. };
  97367. NullEngine.prototype.setArray3 = function (uniform, array) {
  97368. };
  97369. NullEngine.prototype.setArray4 = function (uniform, array) {
  97370. };
  97371. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97372. };
  97373. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97374. };
  97375. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97376. };
  97377. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97378. };
  97379. NullEngine.prototype.setFloat = function (uniform, value) {
  97380. };
  97381. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97382. };
  97383. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97384. };
  97385. NullEngine.prototype.setBool = function (uniform, bool) {
  97386. };
  97387. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97388. };
  97389. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97390. };
  97391. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97392. };
  97393. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97394. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97395. if (this._alphaMode === mode) {
  97396. return;
  97397. }
  97398. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97399. if (!noDepthWriteChange) {
  97400. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97401. }
  97402. this._alphaMode = mode;
  97403. };
  97404. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97405. };
  97406. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97407. if (this.preventCacheWipeBetweenFrames) {
  97408. return;
  97409. }
  97410. this.resetTextureCache();
  97411. this._currentEffect = null;
  97412. if (bruteForce) {
  97413. this._currentProgram = null;
  97414. this._stencilState.reset();
  97415. this._depthCullingState.reset();
  97416. this._alphaState.reset();
  97417. }
  97418. this._cachedVertexBuffers = null;
  97419. this._cachedIndexBuffer = null;
  97420. this._cachedEffectForVertexBuffers = null;
  97421. };
  97422. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97423. };
  97424. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97425. };
  97426. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97427. };
  97428. NullEngine.prototype._createTexture = function () {
  97429. return {};
  97430. };
  97431. NullEngine.prototype._releaseTexture = function (texture) {
  97432. };
  97433. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97435. if (onLoad === void 0) { onLoad = null; }
  97436. if (onError === void 0) { onError = null; }
  97437. if (buffer === void 0) { buffer = null; }
  97438. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97439. var url = String(urlArg);
  97440. texture.url = url;
  97441. texture.generateMipMaps = !noMipmap;
  97442. texture.samplingMode = samplingMode;
  97443. texture.invertY = invertY;
  97444. texture.baseWidth = this._options.textureSize;
  97445. texture.baseHeight = this._options.textureSize;
  97446. texture.width = this._options.textureSize;
  97447. texture.height = this._options.textureSize;
  97448. if (format) {
  97449. texture.format = format;
  97450. }
  97451. texture.isReady = true;
  97452. if (onLoad) {
  97453. onLoad();
  97454. }
  97455. this._internalTexturesCache.push(texture);
  97456. return texture;
  97457. };
  97458. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97459. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97460. if (options !== undefined && typeof options === "object") {
  97461. fullOptions.generateMipMaps = options.generateMipMaps;
  97462. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97463. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97464. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97465. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97466. }
  97467. else {
  97468. fullOptions.generateMipMaps = options;
  97469. fullOptions.generateDepthBuffer = true;
  97470. fullOptions.generateStencilBuffer = false;
  97471. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97472. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97473. }
  97474. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97475. var width = size.width || size;
  97476. var height = size.height || size;
  97477. texture._depthStencilBuffer = {};
  97478. texture._framebuffer = {};
  97479. texture.baseWidth = width;
  97480. texture.baseHeight = height;
  97481. texture.width = width;
  97482. texture.height = height;
  97483. texture.isReady = true;
  97484. texture.samples = 1;
  97485. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97486. texture.samplingMode = fullOptions.samplingMode;
  97487. texture.type = fullOptions.type;
  97488. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97489. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97490. this._internalTexturesCache.push(texture);
  97491. return texture;
  97492. };
  97493. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97494. texture.samplingMode = samplingMode;
  97495. };
  97496. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97497. if (this._currentRenderTarget) {
  97498. this.unBindFramebuffer(this._currentRenderTarget);
  97499. }
  97500. this._currentRenderTarget = texture;
  97501. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97502. if (this._cachedViewport && !forceFullscreenViewport) {
  97503. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97504. }
  97505. };
  97506. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97507. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97508. this._currentRenderTarget = null;
  97509. if (onBeforeUnbind) {
  97510. if (texture._MSAAFramebuffer) {
  97511. this._currentFramebuffer = texture._framebuffer;
  97512. }
  97513. onBeforeUnbind();
  97514. }
  97515. this._currentFramebuffer = null;
  97516. };
  97517. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97518. var vbo = {
  97519. capacity: 1,
  97520. references: 1,
  97521. is32Bits: false
  97522. };
  97523. return vbo;
  97524. };
  97525. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97526. if (offset === void 0) { offset = 0; }
  97527. };
  97528. /**
  97529. * Updates a dynamic vertex buffer.
  97530. * @param vertexBuffer the vertex buffer to update
  97531. * @param data the data used to update the vertex buffer
  97532. * @param byteOffset the byte offset of the data (optional)
  97533. * @param byteLength the byte length of the data (optional)
  97534. */
  97535. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97536. };
  97537. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97538. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97539. this._boundTexturesCache[this._activeChannel] = texture;
  97540. }
  97541. };
  97542. NullEngine.prototype._bindTexture = function (channel, texture) {
  97543. if (channel < 0) {
  97544. return;
  97545. }
  97546. this._bindTextureDirectly(0, texture);
  97547. };
  97548. NullEngine.prototype._releaseBuffer = function (buffer) {
  97549. buffer.references--;
  97550. if (buffer.references === 0) {
  97551. return true;
  97552. }
  97553. return false;
  97554. };
  97555. NullEngine.prototype.releaseEffects = function () {
  97556. };
  97557. return NullEngine;
  97558. }(BABYLON.Engine));
  97559. BABYLON.NullEngine = NullEngine;
  97560. })(BABYLON || (BABYLON = {}));
  97561. //# sourceMappingURL=babylon.nullEngine.js.map
  97562. var BABYLON;
  97563. (function (BABYLON) {
  97564. /**
  97565. * This class can be used to get instrumentation data from a Babylon engine
  97566. */
  97567. var EngineInstrumentation = /** @class */ (function () {
  97568. function EngineInstrumentation(engine) {
  97569. this.engine = engine;
  97570. this._captureGPUFrameTime = false;
  97571. this._gpuFrameTime = new BABYLON.PerfCounter();
  97572. this._captureShaderCompilationTime = false;
  97573. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97574. // Observers
  97575. this._onBeginFrameObserver = null;
  97576. this._onEndFrameObserver = null;
  97577. this._onBeforeShaderCompilationObserver = null;
  97578. this._onAfterShaderCompilationObserver = null;
  97579. }
  97580. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97581. // Properties
  97582. /**
  97583. * Gets the perf counter used for GPU frame time
  97584. */
  97585. get: function () {
  97586. return this._gpuFrameTime;
  97587. },
  97588. enumerable: true,
  97589. configurable: true
  97590. });
  97591. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97592. /**
  97593. * Gets the GPU frame time capture status
  97594. */
  97595. get: function () {
  97596. return this._captureGPUFrameTime;
  97597. },
  97598. /**
  97599. * Enable or disable the GPU frame time capture
  97600. */
  97601. set: function (value) {
  97602. var _this = this;
  97603. if (value === this._captureGPUFrameTime) {
  97604. return;
  97605. }
  97606. this._captureGPUFrameTime = value;
  97607. if (value) {
  97608. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97609. if (!_this._gpuFrameTimeToken) {
  97610. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97611. }
  97612. });
  97613. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  97614. if (!_this._gpuFrameTimeToken) {
  97615. return;
  97616. }
  97617. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  97618. if (time > -1) {
  97619. _this._gpuFrameTimeToken = null;
  97620. _this._gpuFrameTime.fetchNewFrame();
  97621. _this._gpuFrameTime.addCount(time, true);
  97622. }
  97623. });
  97624. }
  97625. else {
  97626. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97627. this._onBeginFrameObserver = null;
  97628. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97629. this._onEndFrameObserver = null;
  97630. }
  97631. },
  97632. enumerable: true,
  97633. configurable: true
  97634. });
  97635. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  97636. /**
  97637. * Gets the perf counter used for shader compilation time
  97638. */
  97639. get: function () {
  97640. return this._shaderCompilationTime;
  97641. },
  97642. enumerable: true,
  97643. configurable: true
  97644. });
  97645. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  97646. /**
  97647. * Gets the shader compilation time capture status
  97648. */
  97649. get: function () {
  97650. return this._captureShaderCompilationTime;
  97651. },
  97652. /**
  97653. * Enable or disable the shader compilation time capture
  97654. */
  97655. set: function (value) {
  97656. var _this = this;
  97657. if (value === this._captureShaderCompilationTime) {
  97658. return;
  97659. }
  97660. this._captureShaderCompilationTime = value;
  97661. if (value) {
  97662. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  97663. _this._shaderCompilationTime.fetchNewFrame();
  97664. _this._shaderCompilationTime.beginMonitoring();
  97665. });
  97666. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  97667. _this._shaderCompilationTime.endMonitoring();
  97668. });
  97669. }
  97670. else {
  97671. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97672. this._onBeforeShaderCompilationObserver = null;
  97673. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97674. this._onAfterShaderCompilationObserver = null;
  97675. }
  97676. },
  97677. enumerable: true,
  97678. configurable: true
  97679. });
  97680. EngineInstrumentation.prototype.dispose = function () {
  97681. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97682. this._onBeginFrameObserver = null;
  97683. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97684. this._onEndFrameObserver = null;
  97685. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97686. this._onBeforeShaderCompilationObserver = null;
  97687. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97688. this._onAfterShaderCompilationObserver = null;
  97689. this.engine = null;
  97690. };
  97691. return EngineInstrumentation;
  97692. }());
  97693. BABYLON.EngineInstrumentation = EngineInstrumentation;
  97694. })(BABYLON || (BABYLON = {}));
  97695. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  97696. var BABYLON;
  97697. (function (BABYLON) {
  97698. /**
  97699. * This class can be used to get instrumentation data from a Babylon engine
  97700. */
  97701. var SceneInstrumentation = /** @class */ (function () {
  97702. function SceneInstrumentation(scene) {
  97703. var _this = this;
  97704. this.scene = scene;
  97705. this._captureActiveMeshesEvaluationTime = false;
  97706. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  97707. this._captureRenderTargetsRenderTime = false;
  97708. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  97709. this._captureFrameTime = false;
  97710. this._frameTime = new BABYLON.PerfCounter();
  97711. this._captureRenderTime = false;
  97712. this._renderTime = new BABYLON.PerfCounter();
  97713. this._captureInterFrameTime = false;
  97714. this._interFrameTime = new BABYLON.PerfCounter();
  97715. this._captureParticlesRenderTime = false;
  97716. this._particlesRenderTime = new BABYLON.PerfCounter();
  97717. this._captureSpritesRenderTime = false;
  97718. this._spritesRenderTime = new BABYLON.PerfCounter();
  97719. this._capturePhysicsTime = false;
  97720. this._physicsTime = new BABYLON.PerfCounter();
  97721. this._captureAnimationsTime = false;
  97722. this._animationsTime = new BABYLON.PerfCounter();
  97723. // Observers
  97724. this._onBeforeActiveMeshesEvaluationObserver = null;
  97725. this._onAfterActiveMeshesEvaluationObserver = null;
  97726. this._onBeforeRenderTargetsRenderObserver = null;
  97727. this._onAfterRenderTargetsRenderObserver = null;
  97728. this._onAfterRenderObserver = null;
  97729. this._onBeforeDrawPhaseObserver = null;
  97730. this._onAfterDrawPhaseObserver = null;
  97731. this._onBeforeAnimationsObserver = null;
  97732. this._onBeforeParticlesRenderingObserver = null;
  97733. this._onAfterParticlesRenderingObserver = null;
  97734. this._onBeforeSpritesRenderingObserver = null;
  97735. this._onAfterSpritesRenderingObserver = null;
  97736. this._onBeforePhysicsObserver = null;
  97737. this._onAfterPhysicsObserver = null;
  97738. this._onAfterAnimationsObserver = null;
  97739. // Before render
  97740. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  97741. if (_this._captureActiveMeshesEvaluationTime) {
  97742. _this._activeMeshesEvaluationTime.fetchNewFrame();
  97743. }
  97744. if (_this._captureRenderTargetsRenderTime) {
  97745. _this._renderTargetsRenderTime.fetchNewFrame();
  97746. }
  97747. if (_this._captureFrameTime) {
  97748. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  97749. _this._frameTime.beginMonitoring();
  97750. }
  97751. if (_this._captureInterFrameTime) {
  97752. _this._interFrameTime.endMonitoring();
  97753. }
  97754. if (_this._captureParticlesRenderTime) {
  97755. _this._particlesRenderTime.fetchNewFrame();
  97756. }
  97757. if (_this._captureSpritesRenderTime) {
  97758. _this._spritesRenderTime.fetchNewFrame();
  97759. }
  97760. if (_this._captureAnimationsTime) {
  97761. _this._animationsTime.beginMonitoring();
  97762. }
  97763. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  97764. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  97765. });
  97766. // After render
  97767. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  97768. if (_this._captureFrameTime) {
  97769. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  97770. _this._frameTime.endMonitoring();
  97771. }
  97772. if (_this._captureRenderTime) {
  97773. _this._renderTime.endMonitoring(false);
  97774. }
  97775. if (_this._captureInterFrameTime) {
  97776. _this._interFrameTime.beginMonitoring();
  97777. }
  97778. });
  97779. }
  97780. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  97781. // Properties
  97782. /**
  97783. * Gets the perf counter used for active meshes evaluation time
  97784. */
  97785. get: function () {
  97786. return this._activeMeshesEvaluationTime;
  97787. },
  97788. enumerable: true,
  97789. configurable: true
  97790. });
  97791. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  97792. /**
  97793. * Gets the active meshes evaluation time capture status
  97794. */
  97795. get: function () {
  97796. return this._captureActiveMeshesEvaluationTime;
  97797. },
  97798. /**
  97799. * Enable or disable the active meshes evaluation time capture
  97800. */
  97801. set: function (value) {
  97802. var _this = this;
  97803. if (value === this._captureActiveMeshesEvaluationTime) {
  97804. return;
  97805. }
  97806. this._captureActiveMeshesEvaluationTime = value;
  97807. if (value) {
  97808. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  97809. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  97810. _this._activeMeshesEvaluationTime.beginMonitoring();
  97811. });
  97812. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  97813. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  97814. _this._activeMeshesEvaluationTime.endMonitoring();
  97815. });
  97816. }
  97817. else {
  97818. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97819. this._onBeforeActiveMeshesEvaluationObserver = null;
  97820. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97821. this._onAfterActiveMeshesEvaluationObserver = null;
  97822. }
  97823. },
  97824. enumerable: true,
  97825. configurable: true
  97826. });
  97827. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  97828. /**
  97829. * Gets the perf counter used for render targets render time
  97830. */
  97831. get: function () {
  97832. return this._renderTargetsRenderTime;
  97833. },
  97834. enumerable: true,
  97835. configurable: true
  97836. });
  97837. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  97838. /**
  97839. * Gets the render targets render time capture status
  97840. */
  97841. get: function () {
  97842. return this._captureRenderTargetsRenderTime;
  97843. },
  97844. /**
  97845. * Enable or disable the render targets render time capture
  97846. */
  97847. set: function (value) {
  97848. var _this = this;
  97849. if (value === this._captureRenderTargetsRenderTime) {
  97850. return;
  97851. }
  97852. this._captureRenderTargetsRenderTime = value;
  97853. if (value) {
  97854. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  97855. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  97856. _this._renderTargetsRenderTime.beginMonitoring();
  97857. });
  97858. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  97859. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  97860. _this._renderTargetsRenderTime.endMonitoring(false);
  97861. });
  97862. }
  97863. else {
  97864. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97865. this._onBeforeRenderTargetsRenderObserver = null;
  97866. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97867. this._onAfterRenderTargetsRenderObserver = null;
  97868. }
  97869. },
  97870. enumerable: true,
  97871. configurable: true
  97872. });
  97873. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  97874. /**
  97875. * Gets the perf counter used for particles render time
  97876. */
  97877. get: function () {
  97878. return this._particlesRenderTime;
  97879. },
  97880. enumerable: true,
  97881. configurable: true
  97882. });
  97883. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  97884. /**
  97885. * Gets the particles render time capture status
  97886. */
  97887. get: function () {
  97888. return this._captureParticlesRenderTime;
  97889. },
  97890. /**
  97891. * Enable or disable the particles render time capture
  97892. */
  97893. set: function (value) {
  97894. var _this = this;
  97895. if (value === this._captureParticlesRenderTime) {
  97896. return;
  97897. }
  97898. this._captureParticlesRenderTime = value;
  97899. if (value) {
  97900. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  97901. BABYLON.Tools.StartPerformanceCounter("Particles");
  97902. _this._particlesRenderTime.beginMonitoring();
  97903. });
  97904. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  97905. BABYLON.Tools.EndPerformanceCounter("Particles");
  97906. _this._particlesRenderTime.endMonitoring(false);
  97907. });
  97908. }
  97909. else {
  97910. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97911. this._onBeforeParticlesRenderingObserver = null;
  97912. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97913. this._onAfterParticlesRenderingObserver = null;
  97914. }
  97915. },
  97916. enumerable: true,
  97917. configurable: true
  97918. });
  97919. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  97920. /**
  97921. * Gets the perf counter used for sprites render time
  97922. */
  97923. get: function () {
  97924. return this._spritesRenderTime;
  97925. },
  97926. enumerable: true,
  97927. configurable: true
  97928. });
  97929. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  97930. /**
  97931. * Gets the sprites render time capture status
  97932. */
  97933. get: function () {
  97934. return this._captureSpritesRenderTime;
  97935. },
  97936. /**
  97937. * Enable or disable the sprites render time capture
  97938. */
  97939. set: function (value) {
  97940. var _this = this;
  97941. if (value === this._captureSpritesRenderTime) {
  97942. return;
  97943. }
  97944. this._captureSpritesRenderTime = value;
  97945. if (value) {
  97946. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  97947. BABYLON.Tools.StartPerformanceCounter("Sprites");
  97948. _this._spritesRenderTime.beginMonitoring();
  97949. });
  97950. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  97951. BABYLON.Tools.EndPerformanceCounter("Sprites");
  97952. _this._spritesRenderTime.endMonitoring(false);
  97953. });
  97954. }
  97955. else {
  97956. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  97957. this._onBeforeSpritesRenderingObserver = null;
  97958. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  97959. this._onAfterSpritesRenderingObserver = null;
  97960. }
  97961. },
  97962. enumerable: true,
  97963. configurable: true
  97964. });
  97965. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  97966. /**
  97967. * Gets the perf counter used for physics time
  97968. */
  97969. get: function () {
  97970. return this._physicsTime;
  97971. },
  97972. enumerable: true,
  97973. configurable: true
  97974. });
  97975. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  97976. /**
  97977. * Gets the physics time capture status
  97978. */
  97979. get: function () {
  97980. return this._capturePhysicsTime;
  97981. },
  97982. /**
  97983. * Enable or disable the physics time capture
  97984. */
  97985. set: function (value) {
  97986. var _this = this;
  97987. if (value === this._capturePhysicsTime) {
  97988. return;
  97989. }
  97990. this._capturePhysicsTime = value;
  97991. if (value) {
  97992. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  97993. BABYLON.Tools.StartPerformanceCounter("Physics");
  97994. _this._physicsTime.beginMonitoring();
  97995. });
  97996. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  97997. BABYLON.Tools.EndPerformanceCounter("Physics");
  97998. _this._physicsTime.endMonitoring();
  97999. });
  98000. }
  98001. else {
  98002. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98003. this._onBeforePhysicsObserver = null;
  98004. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98005. this._onAfterPhysicsObserver = null;
  98006. }
  98007. },
  98008. enumerable: true,
  98009. configurable: true
  98010. });
  98011. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98012. /**
  98013. * Gets the perf counter used for animations time
  98014. */
  98015. get: function () {
  98016. return this._animationsTime;
  98017. },
  98018. enumerable: true,
  98019. configurable: true
  98020. });
  98021. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98022. /**
  98023. * Gets the animations time capture status
  98024. */
  98025. get: function () {
  98026. return this._captureAnimationsTime;
  98027. },
  98028. /**
  98029. * Enable or disable the animations time capture
  98030. */
  98031. set: function (value) {
  98032. var _this = this;
  98033. if (value === this._captureAnimationsTime) {
  98034. return;
  98035. }
  98036. this._captureAnimationsTime = value;
  98037. if (value) {
  98038. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98039. _this._animationsTime.endMonitoring();
  98040. });
  98041. }
  98042. else {
  98043. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98044. this._onAfterAnimationsObserver = null;
  98045. }
  98046. },
  98047. enumerable: true,
  98048. configurable: true
  98049. });
  98050. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98051. /**
  98052. * Gets the perf counter used for frame time capture
  98053. */
  98054. get: function () {
  98055. return this._frameTime;
  98056. },
  98057. enumerable: true,
  98058. configurable: true
  98059. });
  98060. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98061. /**
  98062. * Gets the frame time capture status
  98063. */
  98064. get: function () {
  98065. return this._captureFrameTime;
  98066. },
  98067. /**
  98068. * Enable or disable the frame time capture
  98069. */
  98070. set: function (value) {
  98071. this._captureFrameTime = value;
  98072. },
  98073. enumerable: true,
  98074. configurable: true
  98075. });
  98076. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98077. /**
  98078. * Gets the perf counter used for inter-frames time capture
  98079. */
  98080. get: function () {
  98081. return this._interFrameTime;
  98082. },
  98083. enumerable: true,
  98084. configurable: true
  98085. });
  98086. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98087. /**
  98088. * Gets the inter-frames time capture status
  98089. */
  98090. get: function () {
  98091. return this._captureInterFrameTime;
  98092. },
  98093. /**
  98094. * Enable or disable the inter-frames time capture
  98095. */
  98096. set: function (value) {
  98097. this._captureInterFrameTime = value;
  98098. },
  98099. enumerable: true,
  98100. configurable: true
  98101. });
  98102. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98103. /**
  98104. * Gets the perf counter used for render time capture
  98105. */
  98106. get: function () {
  98107. return this._renderTime;
  98108. },
  98109. enumerable: true,
  98110. configurable: true
  98111. });
  98112. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98113. /**
  98114. * Gets the render time capture status
  98115. */
  98116. get: function () {
  98117. return this._captureRenderTime;
  98118. },
  98119. /**
  98120. * Enable or disable the render time capture
  98121. */
  98122. set: function (value) {
  98123. var _this = this;
  98124. if (value === this._captureRenderTime) {
  98125. return;
  98126. }
  98127. this._captureRenderTime = value;
  98128. if (value) {
  98129. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98130. _this._renderTime.beginMonitoring();
  98131. BABYLON.Tools.StartPerformanceCounter("Main render");
  98132. });
  98133. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98134. _this._renderTime.endMonitoring(false);
  98135. BABYLON.Tools.EndPerformanceCounter("Main render");
  98136. });
  98137. }
  98138. else {
  98139. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98140. this._onBeforeDrawPhaseObserver = null;
  98141. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98142. this._onAfterDrawPhaseObserver = null;
  98143. }
  98144. },
  98145. enumerable: true,
  98146. configurable: true
  98147. });
  98148. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98149. /**
  98150. * Gets the perf counter used for draw calls
  98151. */
  98152. get: function () {
  98153. return this.scene.getEngine()._drawCalls;
  98154. },
  98155. enumerable: true,
  98156. configurable: true
  98157. });
  98158. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98159. /**
  98160. * Gets the perf counter used for texture collisions
  98161. */
  98162. get: function () {
  98163. return this.scene.getEngine()._textureCollisions;
  98164. },
  98165. enumerable: true,
  98166. configurable: true
  98167. });
  98168. SceneInstrumentation.prototype.dispose = function () {
  98169. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98170. this._onAfterRenderObserver = null;
  98171. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98172. this._onBeforeActiveMeshesEvaluationObserver = null;
  98173. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98174. this._onAfterActiveMeshesEvaluationObserver = null;
  98175. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98176. this._onBeforeRenderTargetsRenderObserver = null;
  98177. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98178. this._onAfterRenderTargetsRenderObserver = null;
  98179. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98180. this._onBeforeAnimationsObserver = null;
  98181. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98182. this._onBeforeParticlesRenderingObserver = null;
  98183. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98184. this._onAfterParticlesRenderingObserver = null;
  98185. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98186. this._onBeforeSpritesRenderingObserver = null;
  98187. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98188. this._onAfterSpritesRenderingObserver = null;
  98189. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98190. this._onBeforeDrawPhaseObserver = null;
  98191. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98192. this._onAfterDrawPhaseObserver = null;
  98193. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98194. this._onBeforePhysicsObserver = null;
  98195. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98196. this._onAfterPhysicsObserver = null;
  98197. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98198. this._onAfterAnimationsObserver = null;
  98199. this.scene = null;
  98200. };
  98201. return SceneInstrumentation;
  98202. }());
  98203. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98204. })(BABYLON || (BABYLON = {}));
  98205. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98206. var BABYLON;
  98207. (function (BABYLON) {
  98208. /**
  98209. * @hidden
  98210. **/
  98211. var _TimeToken = /** @class */ (function () {
  98212. function _TimeToken() {
  98213. this._timeElapsedQueryEnded = false;
  98214. }
  98215. return _TimeToken;
  98216. }());
  98217. BABYLON._TimeToken = _TimeToken;
  98218. })(BABYLON || (BABYLON = {}));
  98219. //# sourceMappingURL=babylon.timeToken.js.map
  98220. var BABYLON;
  98221. (function (BABYLON) {
  98222. /**
  98223. * Background material defines definition.
  98224. * @hidden Mainly internal Use
  98225. */
  98226. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98227. __extends(BackgroundMaterialDefines, _super);
  98228. /**
  98229. * Constructor of the defines.
  98230. */
  98231. function BackgroundMaterialDefines() {
  98232. var _this = _super.call(this) || this;
  98233. /**
  98234. * True if the diffuse texture is in use.
  98235. */
  98236. _this.DIFFUSE = false;
  98237. /**
  98238. * The direct UV channel to use.
  98239. */
  98240. _this.DIFFUSEDIRECTUV = 0;
  98241. /**
  98242. * True if the diffuse texture is in gamma space.
  98243. */
  98244. _this.GAMMADIFFUSE = false;
  98245. /**
  98246. * True if the diffuse texture has opacity in the alpha channel.
  98247. */
  98248. _this.DIFFUSEHASALPHA = false;
  98249. /**
  98250. * True if you want the material to fade to transparent at grazing angle.
  98251. */
  98252. _this.OPACITYFRESNEL = false;
  98253. /**
  98254. * True if an extra blur needs to be added in the reflection.
  98255. */
  98256. _this.REFLECTIONBLUR = false;
  98257. /**
  98258. * True if you want the material to fade to reflection at grazing angle.
  98259. */
  98260. _this.REFLECTIONFRESNEL = false;
  98261. /**
  98262. * True if you want the material to falloff as far as you move away from the scene center.
  98263. */
  98264. _this.REFLECTIONFALLOFF = false;
  98265. /**
  98266. * False if the current Webgl implementation does not support the texture lod extension.
  98267. */
  98268. _this.TEXTURELODSUPPORT = false;
  98269. /**
  98270. * True to ensure the data are premultiplied.
  98271. */
  98272. _this.PREMULTIPLYALPHA = false;
  98273. /**
  98274. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98275. */
  98276. _this.USERGBCOLOR = false;
  98277. /**
  98278. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98279. * stays aligned with the desired configuration.
  98280. */
  98281. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98282. /**
  98283. * True to add noise in order to reduce the banding effect.
  98284. */
  98285. _this.NOISE = false;
  98286. /**
  98287. * is the reflection texture in BGR color scheme?
  98288. * Mainly used to solve a bug in ios10 video tag
  98289. */
  98290. _this.REFLECTIONBGR = false;
  98291. _this.IMAGEPROCESSING = false;
  98292. _this.VIGNETTE = false;
  98293. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98294. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98295. _this.TONEMAPPING = false;
  98296. _this.CONTRAST = false;
  98297. _this.COLORCURVES = false;
  98298. _this.COLORGRADING = false;
  98299. _this.COLORGRADING3D = false;
  98300. _this.SAMPLER3DGREENDEPTH = false;
  98301. _this.SAMPLER3DBGRMAP = false;
  98302. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98303. _this.EXPOSURE = false;
  98304. // Reflection.
  98305. _this.REFLECTION = false;
  98306. _this.REFLECTIONMAP_3D = false;
  98307. _this.REFLECTIONMAP_SPHERICAL = false;
  98308. _this.REFLECTIONMAP_PLANAR = false;
  98309. _this.REFLECTIONMAP_CUBIC = false;
  98310. _this.REFLECTIONMAP_PROJECTION = false;
  98311. _this.REFLECTIONMAP_SKYBOX = false;
  98312. _this.REFLECTIONMAP_EXPLICIT = false;
  98313. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98314. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98315. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98316. _this.INVERTCUBICMAP = false;
  98317. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98318. _this.LODINREFLECTIONALPHA = false;
  98319. _this.GAMMAREFLECTION = false;
  98320. _this.RGBDREFLECTION = false;
  98321. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98322. // Default BJS.
  98323. _this.MAINUV1 = false;
  98324. _this.MAINUV2 = false;
  98325. _this.UV1 = false;
  98326. _this.UV2 = false;
  98327. _this.CLIPPLANE = false;
  98328. _this.POINTSIZE = false;
  98329. _this.FOG = false;
  98330. _this.NORMAL = false;
  98331. _this.NUM_BONE_INFLUENCERS = 0;
  98332. _this.BonesPerMesh = 0;
  98333. _this.INSTANCES = false;
  98334. _this.SHADOWFLOAT = false;
  98335. _this.rebuild();
  98336. return _this;
  98337. }
  98338. return BackgroundMaterialDefines;
  98339. }(BABYLON.MaterialDefines));
  98340. /**
  98341. * Background material used to create an efficient environement around your scene.
  98342. */
  98343. var BackgroundMaterial = /** @class */ (function (_super) {
  98344. __extends(BackgroundMaterial, _super);
  98345. /**
  98346. * Instantiates a Background Material in the given scene
  98347. * @param name The friendly name of the material
  98348. * @param scene The scene to add the material to
  98349. */
  98350. function BackgroundMaterial(name, scene) {
  98351. var _this = _super.call(this, name, scene) || this;
  98352. /**
  98353. * Key light Color (multiply against the environement texture)
  98354. */
  98355. _this.primaryColor = BABYLON.Color3.White();
  98356. _this._primaryColorShadowLevel = 0;
  98357. _this._primaryColorHighlightLevel = 0;
  98358. /**
  98359. * Reflection Texture used in the material.
  98360. * Should be author in a specific way for the best result (refer to the documentation).
  98361. */
  98362. _this.reflectionTexture = null;
  98363. /**
  98364. * Reflection Texture level of blur.
  98365. *
  98366. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98367. * texture twice.
  98368. */
  98369. _this.reflectionBlur = 0;
  98370. /**
  98371. * Diffuse Texture used in the material.
  98372. * Should be author in a specific way for the best result (refer to the documentation).
  98373. */
  98374. _this.diffuseTexture = null;
  98375. _this._shadowLights = null;
  98376. /**
  98377. * Specify the list of lights casting shadow on the material.
  98378. * All scene shadow lights will be included if null.
  98379. */
  98380. _this.shadowLights = null;
  98381. /**
  98382. * Helps adjusting the shadow to a softer level if required.
  98383. * 0 means black shadows and 1 means no shadows.
  98384. */
  98385. _this.shadowLevel = 0;
  98386. /**
  98387. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98388. * It is usually zero but might be interesting to modify according to your setup.
  98389. */
  98390. _this.sceneCenter = BABYLON.Vector3.Zero();
  98391. /**
  98392. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98393. * This helps ensuring a nice transition when the camera goes under the ground.
  98394. */
  98395. _this.opacityFresnel = true;
  98396. /**
  98397. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98398. * This helps adding a mirror texture on the ground.
  98399. */
  98400. _this.reflectionFresnel = false;
  98401. /**
  98402. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98403. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98404. */
  98405. _this.reflectionFalloffDistance = 0.0;
  98406. /**
  98407. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98408. */
  98409. _this.reflectionAmount = 1.0;
  98410. /**
  98411. * This specifies the weight of the reflection at grazing angle.
  98412. */
  98413. _this.reflectionReflectance0 = 0.05;
  98414. /**
  98415. * This specifies the weight of the reflection at a perpendicular point of view.
  98416. */
  98417. _this.reflectionReflectance90 = 0.5;
  98418. /**
  98419. * Helps to directly use the maps channels instead of their level.
  98420. */
  98421. _this.useRGBColor = true;
  98422. /**
  98423. * This helps reducing the banding effect that could occur on the background.
  98424. */
  98425. _this.enableNoise = false;
  98426. _this._fovMultiplier = 1.0;
  98427. /**
  98428. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98429. */
  98430. _this.useEquirectangularFOV = false;
  98431. _this._maxSimultaneousLights = 4;
  98432. /**
  98433. * Number of Simultaneous lights allowed on the material.
  98434. */
  98435. _this.maxSimultaneousLights = 4;
  98436. /**
  98437. * Keep track of the image processing observer to allow dispose and replace.
  98438. */
  98439. _this._imageProcessingObserver = null;
  98440. /**
  98441. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98442. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98443. */
  98444. _this.switchToBGR = false;
  98445. // Temp values kept as cache in the material.
  98446. _this._renderTargets = new BABYLON.SmartArray(16);
  98447. _this._reflectionControls = BABYLON.Vector4.Zero();
  98448. _this._white = BABYLON.Color3.White();
  98449. _this._primaryShadowColor = BABYLON.Color3.Black();
  98450. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98451. // Setup the default processing configuration to the scene.
  98452. _this._attachImageProcessingConfiguration(null);
  98453. _this.getRenderTargetTextures = function () {
  98454. _this._renderTargets.reset();
  98455. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98456. _this._renderTargets.push(_this._diffuseTexture);
  98457. }
  98458. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98459. _this._renderTargets.push(_this._reflectionTexture);
  98460. }
  98461. return _this._renderTargets;
  98462. };
  98463. return _this;
  98464. }
  98465. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98466. /**
  98467. * Experimental Internal Use Only.
  98468. *
  98469. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98470. * This acts as a helper to set the primary color to a more "human friendly" value.
  98471. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98472. * output color as close as possible from the chosen value.
  98473. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98474. * part of lighting setup.)
  98475. */
  98476. get: function () {
  98477. return this.__perceptualColor;
  98478. },
  98479. set: function (value) {
  98480. this.__perceptualColor = value;
  98481. this._computePrimaryColorFromPerceptualColor();
  98482. this._markAllSubMeshesAsLightsDirty();
  98483. },
  98484. enumerable: true,
  98485. configurable: true
  98486. });
  98487. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98488. /**
  98489. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98490. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98491. */
  98492. get: function () {
  98493. return this._primaryColorShadowLevel;
  98494. },
  98495. set: function (value) {
  98496. this._primaryColorShadowLevel = value;
  98497. this._computePrimaryColors();
  98498. this._markAllSubMeshesAsLightsDirty();
  98499. },
  98500. enumerable: true,
  98501. configurable: true
  98502. });
  98503. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98504. /**
  98505. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98506. * The primary color is used at the level chosen to define what the white area would look.
  98507. */
  98508. get: function () {
  98509. return this._primaryColorHighlightLevel;
  98510. },
  98511. set: function (value) {
  98512. this._primaryColorHighlightLevel = value;
  98513. this._computePrimaryColors();
  98514. this._markAllSubMeshesAsLightsDirty();
  98515. },
  98516. enumerable: true,
  98517. configurable: true
  98518. });
  98519. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98520. /**
  98521. * Sets the reflection reflectance fresnel values according to the default standard
  98522. * empirically know to work well :-)
  98523. */
  98524. set: function (value) {
  98525. var reflectionWeight = value;
  98526. if (reflectionWeight < 0.5) {
  98527. reflectionWeight = reflectionWeight * 2.0;
  98528. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98529. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98530. }
  98531. else {
  98532. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98533. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98534. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98535. }
  98536. },
  98537. enumerable: true,
  98538. configurable: true
  98539. });
  98540. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98541. /**
  98542. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98543. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98544. * Recommended to be keep at 1.0 except for special cases.
  98545. */
  98546. get: function () {
  98547. return this._fovMultiplier;
  98548. },
  98549. set: function (value) {
  98550. if (isNaN(value)) {
  98551. value = 1.0;
  98552. }
  98553. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98554. },
  98555. enumerable: true,
  98556. configurable: true
  98557. });
  98558. /**
  98559. * Attaches a new image processing configuration to the PBR Material.
  98560. * @param configuration (if null the scene configuration will be use)
  98561. */
  98562. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98563. var _this = this;
  98564. if (configuration === this._imageProcessingConfiguration) {
  98565. return;
  98566. }
  98567. // Detaches observer.
  98568. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98569. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98570. }
  98571. // Pick the scene configuration if needed.
  98572. if (!configuration) {
  98573. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98574. }
  98575. else {
  98576. this._imageProcessingConfiguration = configuration;
  98577. }
  98578. // Attaches observer.
  98579. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98580. _this._computePrimaryColorFromPerceptualColor();
  98581. _this._markAllSubMeshesAsImageProcessingDirty();
  98582. });
  98583. };
  98584. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98585. /**
  98586. * Gets the image processing configuration used either in this material.
  98587. */
  98588. get: function () {
  98589. return this._imageProcessingConfiguration;
  98590. },
  98591. /**
  98592. * Sets the Default image processing configuration used either in the this material.
  98593. *
  98594. * If sets to null, the scene one is in use.
  98595. */
  98596. set: function (value) {
  98597. this._attachImageProcessingConfiguration(value);
  98598. // Ensure the effect will be rebuilt.
  98599. this._markAllSubMeshesAsTexturesDirty();
  98600. },
  98601. enumerable: true,
  98602. configurable: true
  98603. });
  98604. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98605. /**
  98606. * Gets wether the color curves effect is enabled.
  98607. */
  98608. get: function () {
  98609. return this.imageProcessingConfiguration.colorCurvesEnabled;
  98610. },
  98611. /**
  98612. * Sets wether the color curves effect is enabled.
  98613. */
  98614. set: function (value) {
  98615. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  98616. },
  98617. enumerable: true,
  98618. configurable: true
  98619. });
  98620. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  98621. /**
  98622. * Gets wether the color grading effect is enabled.
  98623. */
  98624. get: function () {
  98625. return this.imageProcessingConfiguration.colorGradingEnabled;
  98626. },
  98627. /**
  98628. * Gets wether the color grading effect is enabled.
  98629. */
  98630. set: function (value) {
  98631. this.imageProcessingConfiguration.colorGradingEnabled = value;
  98632. },
  98633. enumerable: true,
  98634. configurable: true
  98635. });
  98636. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  98637. /**
  98638. * Gets wether tonemapping is enabled or not.
  98639. */
  98640. get: function () {
  98641. return this._imageProcessingConfiguration.toneMappingEnabled;
  98642. },
  98643. /**
  98644. * Sets wether tonemapping is enabled or not
  98645. */
  98646. set: function (value) {
  98647. this._imageProcessingConfiguration.toneMappingEnabled = value;
  98648. },
  98649. enumerable: true,
  98650. configurable: true
  98651. });
  98652. ;
  98653. ;
  98654. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  98655. /**
  98656. * The camera exposure used on this material.
  98657. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98658. * This corresponds to a photographic exposure.
  98659. */
  98660. get: function () {
  98661. return this._imageProcessingConfiguration.exposure;
  98662. },
  98663. /**
  98664. * The camera exposure used on this material.
  98665. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98666. * This corresponds to a photographic exposure.
  98667. */
  98668. set: function (value) {
  98669. this._imageProcessingConfiguration.exposure = value;
  98670. },
  98671. enumerable: true,
  98672. configurable: true
  98673. });
  98674. ;
  98675. ;
  98676. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  98677. /**
  98678. * Gets The camera contrast used on this material.
  98679. */
  98680. get: function () {
  98681. return this._imageProcessingConfiguration.contrast;
  98682. },
  98683. /**
  98684. * Sets The camera contrast used on this material.
  98685. */
  98686. set: function (value) {
  98687. this._imageProcessingConfiguration.contrast = value;
  98688. },
  98689. enumerable: true,
  98690. configurable: true
  98691. });
  98692. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  98693. /**
  98694. * Gets the Color Grading 2D Lookup Texture.
  98695. */
  98696. get: function () {
  98697. return this._imageProcessingConfiguration.colorGradingTexture;
  98698. },
  98699. /**
  98700. * Sets the Color Grading 2D Lookup Texture.
  98701. */
  98702. set: function (value) {
  98703. this.imageProcessingConfiguration.colorGradingTexture = value;
  98704. },
  98705. enumerable: true,
  98706. configurable: true
  98707. });
  98708. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  98709. /**
  98710. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98711. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98712. * 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;
  98713. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98714. */
  98715. get: function () {
  98716. return this.imageProcessingConfiguration.colorCurves;
  98717. },
  98718. /**
  98719. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98720. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98721. * 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;
  98722. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98723. */
  98724. set: function (value) {
  98725. this.imageProcessingConfiguration.colorCurves = value;
  98726. },
  98727. enumerable: true,
  98728. configurable: true
  98729. });
  98730. /**
  98731. * The entire material has been created in order to prevent overdraw.
  98732. * @returns false
  98733. */
  98734. BackgroundMaterial.prototype.needAlphaTesting = function () {
  98735. return true;
  98736. };
  98737. /**
  98738. * The entire material has been created in order to prevent overdraw.
  98739. * @returns true if blending is enable
  98740. */
  98741. BackgroundMaterial.prototype.needAlphaBlending = function () {
  98742. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  98743. };
  98744. /**
  98745. * Checks wether the material is ready to be rendered for a given mesh.
  98746. * @param mesh The mesh to render
  98747. * @param subMesh The submesh to check against
  98748. * @param useInstances Specify wether or not the material is used with instances
  98749. * @returns true if all the dependencies are ready (Textures, Effects...)
  98750. */
  98751. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  98752. var _this = this;
  98753. if (useInstances === void 0) { useInstances = false; }
  98754. if (subMesh.effect && this.isFrozen) {
  98755. if (this._wasPreviouslyReady) {
  98756. return true;
  98757. }
  98758. }
  98759. if (!subMesh._materialDefines) {
  98760. subMesh._materialDefines = new BackgroundMaterialDefines();
  98761. }
  98762. var scene = this.getScene();
  98763. var defines = subMesh._materialDefines;
  98764. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  98765. if (defines._renderId === scene.getRenderId()) {
  98766. return true;
  98767. }
  98768. }
  98769. var engine = scene.getEngine();
  98770. // Lights
  98771. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  98772. defines._needNormals = true;
  98773. // Textures
  98774. if (defines._areTexturesDirty) {
  98775. defines._needUVs = false;
  98776. if (scene.texturesEnabled) {
  98777. if (scene.getEngine().getCaps().textureLOD) {
  98778. defines.TEXTURELODSUPPORT = true;
  98779. }
  98780. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98781. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  98782. return false;
  98783. }
  98784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  98785. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  98786. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  98787. defines.OPACITYFRESNEL = this._opacityFresnel;
  98788. }
  98789. else {
  98790. defines.DIFFUSE = false;
  98791. defines.DIFFUSEHASALPHA = false;
  98792. defines.GAMMADIFFUSE = false;
  98793. defines.OPACITYFRESNEL = false;
  98794. }
  98795. var reflectionTexture = this._reflectionTexture;
  98796. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98797. if (!reflectionTexture.isReadyOrNotBlocking()) {
  98798. return false;
  98799. }
  98800. defines.REFLECTION = true;
  98801. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  98802. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  98803. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  98804. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  98805. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  98806. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  98807. defines.REFLECTIONBGR = this.switchToBGR;
  98808. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  98809. defines.INVERTCUBICMAP = true;
  98810. }
  98811. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  98812. switch (reflectionTexture.coordinatesMode) {
  98813. case BABYLON.Texture.EXPLICIT_MODE:
  98814. defines.REFLECTIONMAP_EXPLICIT = true;
  98815. break;
  98816. case BABYLON.Texture.PLANAR_MODE:
  98817. defines.REFLECTIONMAP_PLANAR = true;
  98818. break;
  98819. case BABYLON.Texture.PROJECTION_MODE:
  98820. defines.REFLECTIONMAP_PROJECTION = true;
  98821. break;
  98822. case BABYLON.Texture.SKYBOX_MODE:
  98823. defines.REFLECTIONMAP_SKYBOX = true;
  98824. break;
  98825. case BABYLON.Texture.SPHERICAL_MODE:
  98826. defines.REFLECTIONMAP_SPHERICAL = true;
  98827. break;
  98828. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  98829. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  98830. break;
  98831. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  98832. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  98833. break;
  98834. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  98835. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  98836. break;
  98837. case BABYLON.Texture.CUBIC_MODE:
  98838. case BABYLON.Texture.INVCUBIC_MODE:
  98839. default:
  98840. defines.REFLECTIONMAP_CUBIC = true;
  98841. break;
  98842. }
  98843. if (this.reflectionFresnel) {
  98844. defines.REFLECTIONFRESNEL = true;
  98845. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  98846. this._reflectionControls.x = this.reflectionAmount;
  98847. this._reflectionControls.y = this.reflectionReflectance0;
  98848. this._reflectionControls.z = this.reflectionReflectance90;
  98849. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  98850. }
  98851. else {
  98852. defines.REFLECTIONFRESNEL = false;
  98853. defines.REFLECTIONFALLOFF = false;
  98854. }
  98855. }
  98856. else {
  98857. defines.REFLECTION = false;
  98858. defines.REFLECTIONFRESNEL = false;
  98859. defines.REFLECTIONFALLOFF = false;
  98860. defines.REFLECTIONBLUR = false;
  98861. defines.REFLECTIONMAP_3D = false;
  98862. defines.REFLECTIONMAP_SPHERICAL = false;
  98863. defines.REFLECTIONMAP_PLANAR = false;
  98864. defines.REFLECTIONMAP_CUBIC = false;
  98865. defines.REFLECTIONMAP_PROJECTION = false;
  98866. defines.REFLECTIONMAP_SKYBOX = false;
  98867. defines.REFLECTIONMAP_EXPLICIT = false;
  98868. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98869. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98870. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98871. defines.INVERTCUBICMAP = false;
  98872. defines.REFLECTIONMAP_OPPOSITEZ = false;
  98873. defines.LODINREFLECTIONALPHA = false;
  98874. defines.GAMMAREFLECTION = false;
  98875. defines.RGBDREFLECTION = false;
  98876. }
  98877. }
  98878. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  98879. defines.USERGBCOLOR = this._useRGBColor;
  98880. defines.NOISE = this._enableNoise;
  98881. }
  98882. if (defines._areLightsDirty) {
  98883. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  98884. }
  98885. if (defines._areImageProcessingDirty) {
  98886. if (!this._imageProcessingConfiguration.isReady()) {
  98887. return false;
  98888. }
  98889. this._imageProcessingConfiguration.prepareDefines(defines);
  98890. }
  98891. // Misc.
  98892. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  98893. // Values that need to be evaluated on every frame
  98894. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  98895. // Attribs
  98896. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  98897. if (mesh) {
  98898. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98899. mesh.createNormals(true);
  98900. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  98901. }
  98902. }
  98903. }
  98904. // Get correct effect
  98905. if (defines.isDirty) {
  98906. defines.markAsProcessed();
  98907. scene.resetCachedMaterial();
  98908. // Fallbacks
  98909. var fallbacks = new BABYLON.EffectFallbacks();
  98910. if (defines.FOG) {
  98911. fallbacks.addFallback(0, "FOG");
  98912. }
  98913. if (defines.POINTSIZE) {
  98914. fallbacks.addFallback(1, "POINTSIZE");
  98915. }
  98916. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  98917. if (defines.NUM_BONE_INFLUENCERS > 0) {
  98918. fallbacks.addCPUSkinningFallback(0, mesh);
  98919. }
  98920. //Attributes
  98921. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98922. if (defines.NORMAL) {
  98923. attribs.push(BABYLON.VertexBuffer.NormalKind);
  98924. }
  98925. if (defines.UV1) {
  98926. attribs.push(BABYLON.VertexBuffer.UVKind);
  98927. }
  98928. if (defines.UV2) {
  98929. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98930. }
  98931. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  98932. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  98933. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  98934. "vFogInfos", "vFogColor", "pointSize",
  98935. "vClipPlane", "mBones",
  98936. "vPrimaryColor", "vPrimaryColorShadow",
  98937. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  98938. "shadowLevel", "alpha",
  98939. "vBackgroundCenter", "vReflectionControl",
  98940. "vDiffuseInfos", "diffuseMatrix",
  98941. ];
  98942. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  98943. var uniformBuffers = ["Material", "Scene"];
  98944. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  98945. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  98946. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  98947. uniformsNames: uniforms,
  98948. uniformBuffersNames: uniformBuffers,
  98949. samplers: samplers,
  98950. defines: defines,
  98951. maxSimultaneousLights: this._maxSimultaneousLights
  98952. });
  98953. var onCompiled = function (effect) {
  98954. if (_this.onCompiled) {
  98955. _this.onCompiled(effect);
  98956. }
  98957. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  98958. };
  98959. var join = defines.toString();
  98960. subMesh.setEffect(scene.getEngine().createEffect("background", {
  98961. attributes: attribs,
  98962. uniformsNames: uniforms,
  98963. uniformBuffersNames: uniformBuffers,
  98964. samplers: samplers,
  98965. defines: join,
  98966. fallbacks: fallbacks,
  98967. onCompiled: onCompiled,
  98968. onError: this.onError,
  98969. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  98970. }, engine), defines);
  98971. this.buildUniformLayout();
  98972. }
  98973. if (!subMesh.effect || !subMesh.effect.isReady()) {
  98974. return false;
  98975. }
  98976. defines._renderId = scene.getRenderId();
  98977. this._wasPreviouslyReady = true;
  98978. return true;
  98979. };
  98980. /**
  98981. * Compute the primary color according to the chosen perceptual color.
  98982. */
  98983. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  98984. if (!this.__perceptualColor) {
  98985. return;
  98986. }
  98987. this._primaryColor.copyFrom(this.__perceptualColor);
  98988. // Revert gamma space.
  98989. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  98990. // Revert image processing configuration.
  98991. if (this._imageProcessingConfiguration) {
  98992. // Revert Exposure.
  98993. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  98994. }
  98995. this._computePrimaryColors();
  98996. };
  98997. /**
  98998. * Compute the highlights and shadow colors according to their chosen levels.
  98999. */
  99000. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99001. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99002. return;
  99003. }
  99004. // Find the highlight color based on the configuration.
  99005. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99006. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99007. // Find the shadow color based on the configuration.
  99008. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99009. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99010. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99011. };
  99012. /**
  99013. * Build the uniform buffer used in the material.
  99014. */
  99015. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99016. // Order is important !
  99017. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99018. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99019. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99020. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99021. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99022. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99023. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99024. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99025. this._uniformBuffer.addUniform("pointSize", 1);
  99026. this._uniformBuffer.addUniform("shadowLevel", 1);
  99027. this._uniformBuffer.addUniform("alpha", 1);
  99028. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99029. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99030. this._uniformBuffer.create();
  99031. };
  99032. /**
  99033. * Unbind the material.
  99034. */
  99035. BackgroundMaterial.prototype.unbind = function () {
  99036. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99037. this._uniformBuffer.setTexture("diffuseSampler", null);
  99038. }
  99039. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99040. this._uniformBuffer.setTexture("reflectionSampler", null);
  99041. }
  99042. _super.prototype.unbind.call(this);
  99043. };
  99044. /**
  99045. * Bind only the world matrix to the material.
  99046. * @param world The world matrix to bind.
  99047. */
  99048. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99049. this._activeEffect.setMatrix("world", world);
  99050. };
  99051. /**
  99052. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99053. * @param world The world matrix to bind.
  99054. * @param subMesh The submesh to bind for.
  99055. */
  99056. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99057. var scene = this.getScene();
  99058. var defines = subMesh._materialDefines;
  99059. if (!defines) {
  99060. return;
  99061. }
  99062. var effect = subMesh.effect;
  99063. if (!effect) {
  99064. return;
  99065. }
  99066. this._activeEffect = effect;
  99067. // Matrices
  99068. this.bindOnlyWorldMatrix(world);
  99069. // Bones
  99070. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99071. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99072. if (mustRebind) {
  99073. this._uniformBuffer.bindToEffect(effect, "Material");
  99074. this.bindViewProjection(effect);
  99075. var reflectionTexture = this._reflectionTexture;
  99076. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99077. // Texture uniforms
  99078. if (scene.texturesEnabled) {
  99079. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99080. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99081. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99082. }
  99083. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99084. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99085. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99086. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99087. }
  99088. }
  99089. if (this.shadowLevel > 0) {
  99090. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99091. }
  99092. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99093. // Point size
  99094. if (this.pointsCloud) {
  99095. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99096. }
  99097. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99098. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99099. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99100. }
  99101. else {
  99102. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99103. }
  99104. }
  99105. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99106. // Textures
  99107. if (scene.texturesEnabled) {
  99108. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99109. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99110. }
  99111. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99112. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99113. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99114. }
  99115. else if (!defines.REFLECTIONBLUR) {
  99116. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99117. }
  99118. else {
  99119. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99120. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99121. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99122. }
  99123. if (defines.REFLECTIONFRESNEL) {
  99124. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99125. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99126. }
  99127. }
  99128. }
  99129. // Clip plane
  99130. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99131. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99132. }
  99133. if (mustRebind || !this.isFrozen) {
  99134. if (scene.lightsEnabled) {
  99135. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99136. }
  99137. // View
  99138. this.bindView(effect);
  99139. // Fog
  99140. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99141. // image processing
  99142. this._imageProcessingConfiguration.bind(this._activeEffect);
  99143. }
  99144. this._uniformBuffer.update();
  99145. this._afterBind(mesh);
  99146. };
  99147. /**
  99148. * Dispose the material.
  99149. * @param forceDisposeEffect Force disposal of the associated effect.
  99150. * @param forceDisposeTextures Force disposal of the associated textures.
  99151. */
  99152. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99153. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99154. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99155. if (forceDisposeTextures) {
  99156. if (this.diffuseTexture) {
  99157. this.diffuseTexture.dispose();
  99158. }
  99159. if (this.reflectionTexture) {
  99160. this.reflectionTexture.dispose();
  99161. }
  99162. }
  99163. this._renderTargets.dispose();
  99164. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99165. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99166. }
  99167. _super.prototype.dispose.call(this, forceDisposeEffect);
  99168. };
  99169. /**
  99170. * Clones the material.
  99171. * @param name The cloned name.
  99172. * @returns The cloned material.
  99173. */
  99174. BackgroundMaterial.prototype.clone = function (name) {
  99175. var _this = this;
  99176. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99177. };
  99178. /**
  99179. * Serializes the current material to its JSON representation.
  99180. * @returns The JSON representation.
  99181. */
  99182. BackgroundMaterial.prototype.serialize = function () {
  99183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99184. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99185. return serializationObject;
  99186. };
  99187. /**
  99188. * Gets the class name of the material
  99189. * @returns "BackgroundMaterial"
  99190. */
  99191. BackgroundMaterial.prototype.getClassName = function () {
  99192. return "BackgroundMaterial";
  99193. };
  99194. /**
  99195. * Parse a JSON input to create back a background material.
  99196. * @param source The JSON data to parse
  99197. * @param scene The scene to create the parsed material in
  99198. * @param rootUrl The root url of the assets the material depends upon
  99199. * @returns the instantiated BackgroundMaterial.
  99200. */
  99201. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99202. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99203. };
  99204. /**
  99205. * Standard reflectance value at parallel view angle.
  99206. */
  99207. BackgroundMaterial.StandardReflectance0 = 0.05;
  99208. /**
  99209. * Standard reflectance value at grazing angle.
  99210. */
  99211. BackgroundMaterial.StandardReflectance90 = 0.5;
  99212. __decorate([
  99213. BABYLON.serializeAsColor3()
  99214. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99215. __decorate([
  99216. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99217. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99218. __decorate([
  99219. BABYLON.serializeAsColor3()
  99220. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99221. __decorate([
  99222. BABYLON.serialize()
  99223. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99224. __decorate([
  99225. BABYLON.serialize()
  99226. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99227. __decorate([
  99228. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99229. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99230. __decorate([
  99231. BABYLON.serializeAsTexture()
  99232. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99233. __decorate([
  99234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99235. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99236. __decorate([
  99237. BABYLON.serialize()
  99238. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99239. __decorate([
  99240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99241. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99242. __decorate([
  99243. BABYLON.serializeAsTexture()
  99244. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99245. __decorate([
  99246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99247. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99248. __decorate([
  99249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99250. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99251. __decorate([
  99252. BABYLON.serialize()
  99253. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99254. __decorate([
  99255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99256. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99257. __decorate([
  99258. BABYLON.serializeAsVector3()
  99259. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99260. __decorate([
  99261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99262. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99263. __decorate([
  99264. BABYLON.serialize()
  99265. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99266. __decorate([
  99267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99268. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99269. __decorate([
  99270. BABYLON.serialize()
  99271. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99272. __decorate([
  99273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99274. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99275. __decorate([
  99276. BABYLON.serialize()
  99277. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99278. __decorate([
  99279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99280. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99281. __decorate([
  99282. BABYLON.serialize()
  99283. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99284. __decorate([
  99285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99286. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99287. __decorate([
  99288. BABYLON.serialize()
  99289. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99290. __decorate([
  99291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99292. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99293. __decorate([
  99294. BABYLON.serialize()
  99295. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99296. __decorate([
  99297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99298. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99299. __decorate([
  99300. BABYLON.serialize()
  99301. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99302. __decorate([
  99303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99304. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99305. __decorate([
  99306. BABYLON.serialize()
  99307. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99308. __decorate([
  99309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99310. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99311. __decorate([
  99312. BABYLON.serialize()
  99313. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99314. __decorate([
  99315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99316. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99317. __decorate([
  99318. BABYLON.serializeAsImageProcessingConfiguration()
  99319. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99320. return BackgroundMaterial;
  99321. }(BABYLON.PushMaterial));
  99322. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99323. })(BABYLON || (BABYLON = {}));
  99324. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99325. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99326. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99327. s = arguments[i];
  99328. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99329. t[p] = s[p];
  99330. }
  99331. return t;
  99332. };
  99333. var BABYLON;
  99334. (function (BABYLON) {
  99335. /**
  99336. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99337. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99338. * It also helps with the default setup of your imageProcessing configuration.
  99339. */
  99340. var EnvironmentHelper = /** @class */ (function () {
  99341. /**
  99342. * constructor
  99343. * @param options
  99344. * @param scene The scene to add the material to
  99345. */
  99346. function EnvironmentHelper(options, scene) {
  99347. var _this = this;
  99348. this._errorHandler = function (message, exception) {
  99349. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99350. };
  99351. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99352. this._scene = scene;
  99353. this.onErrorObservable = new BABYLON.Observable();
  99354. this._setupBackground();
  99355. this._setupImageProcessing();
  99356. }
  99357. /**
  99358. * Creates the default options for the helper.
  99359. */
  99360. EnvironmentHelper._getDefaultOptions = function () {
  99361. return {
  99362. createGround: true,
  99363. groundSize: 15,
  99364. groundTexture: this._groundTextureCDNUrl,
  99365. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99366. groundOpacity: 0.9,
  99367. enableGroundShadow: true,
  99368. groundShadowLevel: 0.5,
  99369. enableGroundMirror: false,
  99370. groundMirrorSizeRatio: 0.3,
  99371. groundMirrorBlurKernel: 64,
  99372. groundMirrorAmount: 1,
  99373. groundMirrorFresnelWeight: 1,
  99374. groundMirrorFallOffDistance: 0,
  99375. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99376. groundYBias: 0.00001,
  99377. createSkybox: true,
  99378. skyboxSize: 20,
  99379. skyboxTexture: this._skyboxTextureCDNUrl,
  99380. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99381. backgroundYRotation: 0,
  99382. sizeAuto: true,
  99383. rootPosition: BABYLON.Vector3.Zero(),
  99384. setupImageProcessing: true,
  99385. environmentTexture: this._environmentTextureCDNUrl,
  99386. cameraExposure: 0.8,
  99387. cameraContrast: 1.2,
  99388. toneMappingEnabled: true,
  99389. };
  99390. };
  99391. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99392. /**
  99393. * Gets the root mesh created by the helper.
  99394. */
  99395. get: function () {
  99396. return this._rootMesh;
  99397. },
  99398. enumerable: true,
  99399. configurable: true
  99400. });
  99401. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99402. /**
  99403. * Gets the skybox created by the helper.
  99404. */
  99405. get: function () {
  99406. return this._skybox;
  99407. },
  99408. enumerable: true,
  99409. configurable: true
  99410. });
  99411. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99412. /**
  99413. * Gets the skybox texture created by the helper.
  99414. */
  99415. get: function () {
  99416. return this._skyboxTexture;
  99417. },
  99418. enumerable: true,
  99419. configurable: true
  99420. });
  99421. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99422. /**
  99423. * Gets the skybox material created by the helper.
  99424. */
  99425. get: function () {
  99426. return this._skyboxMaterial;
  99427. },
  99428. enumerable: true,
  99429. configurable: true
  99430. });
  99431. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99432. /**
  99433. * Gets the ground mesh created by the helper.
  99434. */
  99435. get: function () {
  99436. return this._ground;
  99437. },
  99438. enumerable: true,
  99439. configurable: true
  99440. });
  99441. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99442. /**
  99443. * Gets the ground texture created by the helper.
  99444. */
  99445. get: function () {
  99446. return this._groundTexture;
  99447. },
  99448. enumerable: true,
  99449. configurable: true
  99450. });
  99451. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99452. /**
  99453. * Gets the ground mirror created by the helper.
  99454. */
  99455. get: function () {
  99456. return this._groundMirror;
  99457. },
  99458. enumerable: true,
  99459. configurable: true
  99460. });
  99461. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99462. /**
  99463. * Gets the ground mirror render list to helps pushing the meshes
  99464. * you wish in the ground reflection.
  99465. */
  99466. get: function () {
  99467. if (this._groundMirror) {
  99468. return this._groundMirror.renderList;
  99469. }
  99470. return null;
  99471. },
  99472. enumerable: true,
  99473. configurable: true
  99474. });
  99475. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99476. /**
  99477. * Gets the ground material created by the helper.
  99478. */
  99479. get: function () {
  99480. return this._groundMaterial;
  99481. },
  99482. enumerable: true,
  99483. configurable: true
  99484. });
  99485. /**
  99486. * Updates the background according to the new options
  99487. * @param options
  99488. */
  99489. EnvironmentHelper.prototype.updateOptions = function (options) {
  99490. var newOptions = __assign({}, this._options, options);
  99491. if (this._ground && !newOptions.createGround) {
  99492. this._ground.dispose();
  99493. this._ground = null;
  99494. }
  99495. if (this._groundMaterial && !newOptions.createGround) {
  99496. this._groundMaterial.dispose();
  99497. this._groundMaterial = null;
  99498. }
  99499. if (this._groundTexture) {
  99500. if (this._options.groundTexture != newOptions.groundTexture) {
  99501. this._groundTexture.dispose();
  99502. this._groundTexture = null;
  99503. }
  99504. }
  99505. if (this._skybox && !newOptions.createSkybox) {
  99506. this._skybox.dispose();
  99507. this._skybox = null;
  99508. }
  99509. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99510. this._skyboxMaterial.dispose();
  99511. this._skyboxMaterial = null;
  99512. }
  99513. if (this._skyboxTexture) {
  99514. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99515. this._skyboxTexture.dispose();
  99516. this._skyboxTexture = null;
  99517. }
  99518. }
  99519. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99520. this._groundMirror.dispose();
  99521. this._groundMirror = null;
  99522. }
  99523. if (this._scene.environmentTexture) {
  99524. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99525. this._scene.environmentTexture.dispose();
  99526. }
  99527. }
  99528. this._options = newOptions;
  99529. this._setupBackground();
  99530. this._setupImageProcessing();
  99531. };
  99532. /**
  99533. * Sets the primary color of all the available elements.
  99534. * @param color the main color to affect to the ground and the background
  99535. */
  99536. EnvironmentHelper.prototype.setMainColor = function (color) {
  99537. if (this.groundMaterial) {
  99538. this.groundMaterial.primaryColor = color;
  99539. }
  99540. if (this.skyboxMaterial) {
  99541. this.skyboxMaterial.primaryColor = color;
  99542. }
  99543. if (this.groundMirror) {
  99544. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99545. }
  99546. };
  99547. /**
  99548. * Setup the image processing according to the specified options.
  99549. */
  99550. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99551. if (this._options.setupImageProcessing) {
  99552. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99553. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99554. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99555. this._setupEnvironmentTexture();
  99556. }
  99557. };
  99558. /**
  99559. * Setup the environment texture according to the specified options.
  99560. */
  99561. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99562. if (this._scene.environmentTexture) {
  99563. return;
  99564. }
  99565. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99566. this._scene.environmentTexture = this._options.environmentTexture;
  99567. return;
  99568. }
  99569. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99570. this._scene.environmentTexture = environmentTexture;
  99571. };
  99572. /**
  99573. * Setup the background according to the specified options.
  99574. */
  99575. EnvironmentHelper.prototype._setupBackground = function () {
  99576. if (!this._rootMesh) {
  99577. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99578. }
  99579. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99580. var sceneSize = this._getSceneSize();
  99581. if (this._options.createGround) {
  99582. this._setupGround(sceneSize);
  99583. this._setupGroundMaterial();
  99584. this._setupGroundDiffuseTexture();
  99585. if (this._options.enableGroundMirror) {
  99586. this._setupGroundMirrorTexture(sceneSize);
  99587. }
  99588. this._setupMirrorInGroundMaterial();
  99589. }
  99590. if (this._options.createSkybox) {
  99591. this._setupSkybox(sceneSize);
  99592. this._setupSkyboxMaterial();
  99593. this._setupSkyboxReflectionTexture();
  99594. }
  99595. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99596. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99597. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99598. };
  99599. /**
  99600. * Get the scene sizes according to the setup.
  99601. */
  99602. EnvironmentHelper.prototype._getSceneSize = function () {
  99603. var _this = this;
  99604. var groundSize = this._options.groundSize;
  99605. var skyboxSize = this._options.skyboxSize;
  99606. var rootPosition = this._options.rootPosition;
  99607. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  99608. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99609. }
  99610. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  99611. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  99612. });
  99613. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  99614. if (this._options.sizeAuto) {
  99615. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  99616. this._scene.activeCamera.upperRadiusLimit) {
  99617. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  99618. skyboxSize = groundSize;
  99619. }
  99620. var sceneDiagonalLenght = sceneDiagonal.length();
  99621. if (sceneDiagonalLenght > groundSize) {
  99622. groundSize = sceneDiagonalLenght * 2;
  99623. skyboxSize = groundSize;
  99624. }
  99625. // 10 % bigger.
  99626. groundSize *= 1.1;
  99627. skyboxSize *= 1.5;
  99628. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  99629. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  99630. }
  99631. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99632. };
  99633. /**
  99634. * Setup the ground according to the specified options.
  99635. */
  99636. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  99637. var _this = this;
  99638. if (!this._ground) {
  99639. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  99640. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  99641. this._ground.parent = this._rootMesh;
  99642. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  99643. }
  99644. this._ground.receiveShadows = this._options.enableGroundShadow;
  99645. };
  99646. /**
  99647. * Setup the ground material according to the specified options.
  99648. */
  99649. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  99650. if (!this._groundMaterial) {
  99651. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  99652. }
  99653. this._groundMaterial.alpha = this._options.groundOpacity;
  99654. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  99655. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  99656. this._groundMaterial.primaryColor = this._options.groundColor;
  99657. this._groundMaterial.useRGBColor = false;
  99658. this._groundMaterial.enableNoise = true;
  99659. if (this._ground) {
  99660. this._ground.material = this._groundMaterial;
  99661. }
  99662. };
  99663. /**
  99664. * Setup the ground diffuse texture according to the specified options.
  99665. */
  99666. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  99667. if (!this._groundMaterial) {
  99668. return;
  99669. }
  99670. if (this._groundTexture) {
  99671. return;
  99672. }
  99673. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  99674. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  99675. return;
  99676. }
  99677. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99678. diffuseTexture.gammaSpace = false;
  99679. diffuseTexture.hasAlpha = true;
  99680. this._groundMaterial.diffuseTexture = diffuseTexture;
  99681. };
  99682. /**
  99683. * Setup the ground mirror texture according to the specified options.
  99684. */
  99685. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  99686. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99687. if (!this._groundMirror) {
  99688. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  99689. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  99690. this._groundMirror.anisotropicFilteringLevel = 1;
  99691. this._groundMirror.wrapU = wrapping;
  99692. this._groundMirror.wrapV = wrapping;
  99693. this._groundMirror.gammaSpace = false;
  99694. if (this._groundMirror.renderList) {
  99695. for (var i = 0; i < this._scene.meshes.length; i++) {
  99696. var mesh = this._scene.meshes[i];
  99697. if (mesh !== this._ground &&
  99698. mesh !== this._skybox &&
  99699. mesh !== this._rootMesh) {
  99700. this._groundMirror.renderList.push(mesh);
  99701. }
  99702. }
  99703. }
  99704. }
  99705. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  99706. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  99707. };
  99708. /**
  99709. * Setup the ground to receive the mirror texture.
  99710. */
  99711. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  99712. if (this._groundMaterial) {
  99713. this._groundMaterial.reflectionTexture = this._groundMirror;
  99714. this._groundMaterial.reflectionFresnel = true;
  99715. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  99716. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  99717. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  99718. }
  99719. };
  99720. /**
  99721. * Setup the skybox according to the specified options.
  99722. */
  99723. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  99724. var _this = this;
  99725. if (!this._skybox) {
  99726. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  99727. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  99728. }
  99729. this._skybox.parent = this._rootMesh;
  99730. };
  99731. /**
  99732. * Setup the skybox material according to the specified options.
  99733. */
  99734. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  99735. if (!this._skybox) {
  99736. return;
  99737. }
  99738. if (!this._skyboxMaterial) {
  99739. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  99740. }
  99741. this._skyboxMaterial.useRGBColor = false;
  99742. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  99743. this._skyboxMaterial.enableNoise = true;
  99744. this._skybox.material = this._skyboxMaterial;
  99745. };
  99746. /**
  99747. * Setup the skybox reflection texture according to the specified options.
  99748. */
  99749. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  99750. if (!this._skyboxMaterial) {
  99751. return;
  99752. }
  99753. if (this._skyboxTexture) {
  99754. return;
  99755. }
  99756. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  99757. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  99758. return;
  99759. }
  99760. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99761. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  99762. this._skyboxTexture.gammaSpace = false;
  99763. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  99764. };
  99765. /**
  99766. * Dispose all the elements created by the Helper.
  99767. */
  99768. EnvironmentHelper.prototype.dispose = function () {
  99769. if (this._groundMaterial) {
  99770. this._groundMaterial.dispose(true, true);
  99771. }
  99772. if (this._skyboxMaterial) {
  99773. this._skyboxMaterial.dispose(true, true);
  99774. }
  99775. this._rootMesh.dispose(false);
  99776. };
  99777. /**
  99778. * Default ground texture URL.
  99779. */
  99780. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  99781. /**
  99782. * Default skybox texture URL.
  99783. */
  99784. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  99785. /**
  99786. * Default environment texture URL.
  99787. */
  99788. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  99789. return EnvironmentHelper;
  99790. }());
  99791. BABYLON.EnvironmentHelper = EnvironmentHelper;
  99792. })(BABYLON || (BABYLON = {}));
  99793. //# sourceMappingURL=babylon.environmentHelper.js.map
  99794. var BABYLON;
  99795. (function (BABYLON) {
  99796. /**
  99797. * This class is made for on one-liner static method to help creating particle systems.
  99798. */
  99799. var ParticleHelper = /** @class */ (function () {
  99800. function ParticleHelper() {
  99801. }
  99802. /**
  99803. * This is the main static method (one-liner) of this helper to create different particle systems.
  99804. * @param type This string represents the type to the particle system to create
  99805. * @param emitter The object where the particle system will start to emit from.
  99806. * @param scene The scene where the particle system should live.
  99807. * @param gpu If the system will use gpu.
  99808. * @returns the ParticleSystem created.
  99809. */
  99810. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  99811. var _this = this;
  99812. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  99813. if (gpu === void 0) { gpu = false; }
  99814. return new Promise(function (resolve, reject) {
  99815. if (scene) {
  99816. _this._scene = scene;
  99817. }
  99818. else {
  99819. return reject("A particle system need a scene.");
  99820. }
  99821. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  99822. return reject("Particle system with GPU is not supported.");
  99823. }
  99824. _this._emitter = emitter;
  99825. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  99826. var newData = JSON.parse(data.toString());
  99827. return resolve(_this._createSystem(newData));
  99828. }, undefined, undefined, undefined, function (req, exception) {
  99829. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  99830. });
  99831. });
  99832. };
  99833. ParticleHelper._createSystem = function (data) {
  99834. // Create a particle system
  99835. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  99836. // Texture of each particle
  99837. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  99838. // Where the particles come from
  99839. system.emitter = this._emitter; // the starting object, the emitter
  99840. // Colors of all particles
  99841. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  99842. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  99843. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  99844. // Size of each particle (random between...
  99845. system.minSize = data.minSize;
  99846. system.maxSize = data.maxSize;
  99847. // Life time of each particle (random between...
  99848. system.minLifeTime = data.minLifeTime;
  99849. system.maxLifeTime = data.maxLifeTime;
  99850. // Emission rate
  99851. system.emitRate = data.emitRate;
  99852. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  99853. system.blendMode = data.blendMode;
  99854. // Set the gravity of all particles
  99855. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  99856. // Angular speed, in radians
  99857. system.minAngularSpeed = data.minAngularSpeed;
  99858. system.maxAngularSpeed = data.maxAngularSpeed;
  99859. // Speed
  99860. system.minEmitPower = data.minEmitPower;
  99861. system.maxEmitPower = data.maxEmitPower;
  99862. system.updateSpeed = data.updateSpeed;
  99863. switch (data.emitterType) {
  99864. case "box":
  99865. if (!data.direction1 || !data.direction2) {
  99866. throw new Error("Directions are missing in this particle system.");
  99867. }
  99868. if (!data.minEmitBox || !data.maxEmitBox) {
  99869. throw new Error("EmitBox is missing in this particle system.");
  99870. }
  99871. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  99872. break;
  99873. case "sphere":
  99874. system.createSphereEmitter(data.radius);
  99875. break;
  99876. case "directed_sphere":
  99877. if (!data.direction1 || !data.direction2) {
  99878. throw new Error("Directions are missing in this particle system.");
  99879. }
  99880. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  99881. break;
  99882. case "cone":
  99883. system.createConeEmitter(data.radius, data.angle);
  99884. break;
  99885. default:
  99886. break;
  99887. }
  99888. return system;
  99889. };
  99890. /**
  99891. * Base Assets URL.
  99892. */
  99893. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  99894. return ParticleHelper;
  99895. }());
  99896. BABYLON.ParticleHelper = ParticleHelper;
  99897. })(BABYLON || (BABYLON = {}));
  99898. //# sourceMappingURL=babylon.particleHelper.js.map
  99899. var BABYLON;
  99900. (function (BABYLON) {
  99901. /**
  99902. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  99903. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  99904. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  99905. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  99906. */
  99907. var VideoDome = /** @class */ (function (_super) {
  99908. __extends(VideoDome, _super);
  99909. /**
  99910. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  99911. * @param name Element's name, child elements will append suffixes for their own names.
  99912. * @param urlsOrVideo defines the url(s) or the video element to use
  99913. * @param options An object containing optional or exposed sub element properties
  99914. */
  99915. function VideoDome(name, urlsOrVideo, options, scene) {
  99916. var _this = _super.call(this, name, scene) || this;
  99917. // set defaults and manage values
  99918. name = name || "videoDome";
  99919. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  99920. options.clickToPlay = Boolean(options.clickToPlay);
  99921. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  99922. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  99923. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  99924. // create
  99925. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  99926. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  99927. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  99928. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  99929. flat: false,
  99930. radius: options.size,
  99931. subdivisions: options.resolution,
  99932. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  99933. }, scene);
  99934. // configure material
  99935. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  99936. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  99937. material.reflectionTexture = _this._videoTexture;
  99938. material.useEquirectangularFOV = true;
  99939. material.fovMultiplier = 1.0;
  99940. // configure mesh
  99941. _this._mesh.material = material;
  99942. _this._mesh.parent = _this;
  99943. // optional configuration
  99944. if (options.clickToPlay) {
  99945. scene.onPointerUp = function () {
  99946. _this._videoTexture.video.play();
  99947. };
  99948. }
  99949. return _this;
  99950. }
  99951. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  99952. /**
  99953. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99954. * Also see the options.resolution property.
  99955. */
  99956. get: function () {
  99957. return this._material.fovMultiplier;
  99958. },
  99959. set: function (value) {
  99960. this._material.fovMultiplier = value;
  99961. },
  99962. enumerable: true,
  99963. configurable: true
  99964. });
  99965. /**
  99966. * Releases resources associated with this node.
  99967. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  99968. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  99969. */
  99970. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  99971. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  99972. this._videoTexture.dispose();
  99973. this._mesh.dispose();
  99974. this._material.dispose();
  99975. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  99976. };
  99977. return VideoDome;
  99978. }(BABYLON.Node));
  99979. BABYLON.VideoDome = VideoDome;
  99980. })(BABYLON || (BABYLON = {}));
  99981. //# sourceMappingURL=babylon.videoDome.js.map
  99982. var BABYLON;
  99983. (function (BABYLON) {
  99984. /**
  99985. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  99986. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  99987. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  99988. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  99989. */
  99990. var PhotoDome = /** @class */ (function (_super) {
  99991. __extends(PhotoDome, _super);
  99992. /**
  99993. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  99994. * @param name Element's name, child elements will append suffixes for their own names.
  99995. * @param urlsOfPhoto define the url of the photo to display
  99996. * @param options An object containing optional or exposed sub element properties
  99997. */
  99998. function PhotoDome(name, urlOfPhoto, options, scene) {
  99999. var _this = _super.call(this, name, scene) || this;
  100000. // set defaults and manage values
  100001. name = name || "photoDome";
  100002. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100003. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100004. // create
  100005. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100006. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100007. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100008. flat: false,
  100009. radius: options.size,
  100010. subdivisions: options.resolution,
  100011. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100012. }, scene);
  100013. // configure material
  100014. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100015. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100016. material.reflectionTexture = _this._photoTexture;
  100017. material.useEquirectangularFOV = true;
  100018. material.fovMultiplier = 1.0;
  100019. // configure mesh
  100020. _this._mesh.material = material;
  100021. _this._mesh.parent = _this;
  100022. return _this;
  100023. }
  100024. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100025. /**
  100026. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100027. * Also see the options.resolution property.
  100028. */
  100029. get: function () {
  100030. return this._material.fovMultiplier;
  100031. },
  100032. set: function (value) {
  100033. this._material.fovMultiplier = value;
  100034. },
  100035. enumerable: true,
  100036. configurable: true
  100037. });
  100038. /**
  100039. * Releases resources associated with this node.
  100040. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100041. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100042. */
  100043. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100044. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100045. this._photoTexture.dispose();
  100046. this._mesh.dispose();
  100047. this._material.dispose();
  100048. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100049. };
  100050. return PhotoDome;
  100051. }(BABYLON.Node));
  100052. BABYLON.PhotoDome = PhotoDome;
  100053. })(BABYLON || (BABYLON = {}));
  100054. //# sourceMappingURL=babylon.photoDome.js.map
  100055. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\nvec2 cornerPos=offset*size;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  100056. 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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb*rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  100057. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  100058. globalObject["BABYLON"] = BABYLON;
  100059. //backwards compatibility
  100060. if(typeof earcut !== 'undefined') {
  100061. globalObject["Earcut"] = {
  100062. earcut: earcut
  100063. };
  100064. }
  100065. return BABYLON;
  100066. });